如何解析 Powershell 脚本块中的变量

ala*_*ree 5 powershell

鉴于我有:

$a = "world"
$b = { write-host "hello $a" }
Run Code Online (Sandbox Code Playgroud)

如何获取脚本块的解析文本,它应该是包含 write-host 的 entre 字符串:

write-host "hello world"
Run Code Online (Sandbox Code Playgroud)

更新:补充说明

如果你只是打印$b你会得到变量而不是解析值

write-host "hello $a"
Run Code Online (Sandbox Code Playgroud)

如果您执行脚本块并& $b获得打印值,而不是脚本块的内容:

hello world
Run Code Online (Sandbox Code Playgroud)

这个问题正在寻找一个字符串,其中包含带有评估变量的脚本块的内容,它是:

write-host "hello world"
Run Code Online (Sandbox Code Playgroud)

Adm*_*ngs 9

与原始问题一样,如果您的整个脚本块内容不是字符串(但您希望它是)并且您需要在脚本块中进行变量替换,则可以使用以下内容:

$ExecutionContext.InvokeCommand.ExpandString($b)
Run Code Online (Sandbox Code Playgroud)

调用.InvokeCommand.ExpandString($b)当前执行上下文将使用当前作用域中的变量进行替换。

以下是创建脚本块并检索其内容的一种方法:

$a = "world"
$b = [ScriptBlock]::create("write-host hello $a")
$b

write-host hello world
Run Code Online (Sandbox Code Playgroud)

您也可以使用 scriptblock 符号{}来完成同样的事情,但您需要使用&call 运算符:

$a = "world"
$b = {"write-host hello $a"}
& $b

write-host hello world
Run Code Online (Sandbox Code Playgroud)

使用上述方法的一个特点是,如果您随时更改 的值,$a然后再次调用脚本块,输出将更新如下:

$a = "world"
$b = {"write-host hello $a"}
& $b
write-host hello world
$a = "hi"
& $b
write-host hello hi
Run Code Online (Sandbox Code Playgroud)

GetNewClosure()方法可用于创建上述脚本块的克隆,以获取脚本块当前评估的理论快照。它将不受$a代码稍后更改值的影响:

$b = {"write-host hello $a"}.GetNewClosure()
& $b
write-host hello world
$a = "new world"
& $b
write-host hello world
Run Code Online (Sandbox Code Playgroud)

{}符号表示您可能已经知道的脚本块对象。可以将其传递给Invoke-Command,从而打开其他选项。您还可以在脚本块内创建可以稍后传入的参数。有关详细信息,请参阅about_Script_Blocks

  • 找到了一个简短的答案。只需运行这个`$executioncontext.invokecommand.expandstring($b)`。 (4认同)