我有一个编辑注册表的 PowerShell 脚本,因此需要以管理员身份运行。为此,我从正在运行的 PowerShell 脚本启动一个新的 PowerShell 进程,并使用其中包含函数的脚本块传递部分注册表项路径。当我在该函数中使用双引号时,PowerShell 尝试将它们解释为命令,而不是字符串。如果我使用单引号,那么一切都会正常。
我创建了一个简单的示例 powershell 脚本来重现该问题。这是片段:
$ScriptBlock = {
function Test
{
$status = "This is a string"
Write-Output $status
}
}
Start-Process -FilePath PowerShell -ArgumentList "-NoExit -NoProfile -ExecutionPolicy Bypass -Command & {$ScriptBlock Test}"
因此,在新的PowerShell进程中,它会首先在脚本块中定义代码,然后调用Test方法,它会产生以下错误:
This :术语“This”未被识别为 cmdlet 的名称,
函数、脚本文件或可运行程序。检查拼写
名称,或者如果包含路径,请验证路径是否正确并且
再试一次。
所以它试图将字符串视为命令,就像我刚刚输入的一样This is a string
在我的脚本中单独一行。
如果我改变线路
$status = "This is a string"
to
$status = 'This is a string'
脚本按预期工作并简单地输出字符串This is a string
.
我注意到的另一个奇怪的问题是,如果我不使用变量而只使用:
Write-Output "This is a string"
然后它在单独的行上输出每个单词,如下所示:
This
is
a
string
但如果我使用这样的单引号:
Write-Output 'This is a string'
然后它会按预期在一行上输出整个句子。
有谁知道为什么 PowerShell 在这些情况下表现得很奇怪?
Answer
正如 TessellationHeckler 提到的,解决方案是将所有双引号括在双双引号、单引号中,或者您可以使用方括号。
所以在我的例子中,你会改变:
$status = "This is a string"
to this:
$status = """This is a string"""
or this:
$status = '"This is a string"'
or this:
$status = {"This is a string"}
如果您想计算字符串中的变量(即查看变量的值),那么您必须使用双双引号方法:
$status = """This is a string that evaluates $someVariable"""
仍然不确定这是一个错误还是设计使然,但至少我们有一个解决方法,因为这解决了我上面描述的两个问题。