Powershell 测试脚本返回错误“术语‘=’未被识别为 cmdlet、函数、脚本文件或可操作程序的名称”

Powershell 测试脚本返回错误“术语‘=’未被识别为 cmdlet、函数、脚本文件或可操作程序的名称”

powershell 用户!如果我将 powershell 作为 shell 运行并逐个输入命令 - 一切都很好。但如果我将命令放入 .ps1 文件并尝试执行它,我会收到奇怪的错误:

The term '=' is not recognized as the name of a cmdlet, function, script file, or operable program

我运行的测试脚本:

echo "$pw = 2" > ./test.ps1
echo '$pw' >> ./test.ps1
pwsh ./test.ps1

我在 Linux 上使用 pwsh(安装自https://packages.microsoft.com/rhel/7/prod/) 如果有关系的话。

尝试使用“$pw=2”——结果相同。

是的,我知道设置和获取变量的长格式:

echo "set-variable -name 'pw' -value '2'" > ./test.ps1
echo "get-variable -name 'pw'" >> ./test.ps1
pwsh ./test.ps1

可以。但我想要更复杂的脚本,其中 get-variable 几乎不能使用。

请帮忙-我做错了什么?

答案1

您需要转义$表示变量名称的美元符号。

# command                       # result
Set-StrictMode -Off             # uninitialized variables are assumed to have a value of 0 (zero) or $null
echo "$pw = 2"                  #  = 2
Set-StrictMode -Version Latest  # Selects the latest (most strict) version available
echo "$pw = 2"                  # throws an error: The variable '$pw' cannot be retrieved because it has not been set.
echo '$pw = 2'                  # $pw = 2       (used single quotes)
echo "`$pw = 2"                 # $pw = 2       (used backtick escape character)

编辑上述示例是在 Windows Powershell 中测试的。然而,在 WSL Ubuntushell 中省略所有Set-StrictMode内容也能得到相同的结果使用\反斜杠转义字符如下:

# command                       # result
echo "$pw = 2"                  #  = 2
echo '$pw = 2'                  # $pw = 2       (used single quotes)
echo "\$pw = 2"                 # $pw = 2       (used backslash escape character)

参考:

相关内容