gpt4 book ai didi

string - PowerShell 使用 Start-Process 在脚本 block 中执行函数会用双引号做一些奇怪的事情

转载 作者:行者123 更新时间:2023-12-04 15:34:15 24 4
gpt4 key购买 nike

我有一个用于编辑注册表的 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 : The term 'This' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.



所以它试图将字符串视为逗号,就像我刚刚输入了 This is a string 一样自己在我的脚本中的一个新行上。

如果我改变线
$status = "This is a string"


$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 在这些情况下会表现得很奇怪吗?

回答

因此,正如 TessellatingHeckler 所提到的,解决方案是用双双引号、单引号或您可以使用括号将任何双引号括起来。

所以在我的例子中,你会改变:
$status = "This is a string"

对此:
$status = """This is a string"""

或这个:
$status = '"This is a string"'

或这个:
$status = {"This is a string"}

如果您想评估字符串中的变量(即查看变量的值),那么您必须使用双双引号方法:
$status = """This is a string that evaluates $someVariable"""

仍然不确定这是错误还是设计使然,但至少我们有一个解决方法,因为这解决了我上面描述的两个问题。

最佳答案

如果我将您的脚本更改为

-Command $ScriptBlock

运行它,并让它打开一个新的 shell 窗口,然后运行
gci function:test | fl 

要在新窗口中查看函数定义,显示的代码是
$status = This is a string

对它显示的单引号版本进行相同的测试
$status = 'This is a string'

所以它失去了双引号。用双引号转义它们
$status = """This is a string"""

他们通过OK。此外,即使脚本块是编译代码,但在我看来,如果将它们展开为字符串,它们就像是作为文本嵌入的:
> $s = { "hello" }
> "---$s---"
---"hello"---

所以我认为你遇到了这种引用问题: PowerShell stripping double quotes from command line arguments以及 Droj 的回答,特别是说“将参数发送到外部程序的奇怪之处在于有额外的报价评估级别。我不知道这是否是一个错误,但我猜它不会改变,因为当您使用 Start-Process 并传入参数时,行为是相同的。”。

PowerShell 将脚本块作为字符串扩展到您的命令中,然后将字符串周围的单引号重新解释为带引号的参数并在调用中的某处删除。哪个是已知问题、错误或设计,取决于您阅读链接的连接文章的方式。

关于string - PowerShell 使用 Start-Process 在脚本 block 中执行函数会用双引号做一些奇怪的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22544930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com