【问题标题】:How to resolve variables in a Powershell script block如何解析 Powershell 脚本块中的变量
【发布时间】:2019-07-30 12:10:15
【问题描述】:

鉴于我有:

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

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

write-host "hello world"

更新:补充说明

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

write-host "hello $a"

如果您使用& $b 执行脚本块,您会得到打印的值,而不是脚本块的内容:

hello world

这个问题是寻找一个包含脚本块内容和评估变量的字符串,即:

write-host "hello world"

【问题讨论】:

  • 你有一个 scriptblock 并且你需要调用/运行这个 scriptblock。 [grin] 简单地调用保存脚本块的 $Var 将给出文字内容,而不是运行它。你可以这样运行它...Invoke-Command -ScriptBlock $b output = hello world
  • 我不相信这是重复的,因为我没有执行脚本块 - 我想要一个带有评估变量的语法字符串
  • @Lee_Dailey - 从答案中可以看出,您可以使用$ExecutionContext.InvokeCommand.ExpandString($b)
  • @alasairtree - 哈!我学到了一些新东西! [grin] 我会尽快删除这条评论 - 并立即删除我的错误评论以避免混淆。

标签: powershell


【解决方案1】:

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

$ExecutionContext.InvokeCommand.ExpandString($b)

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

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

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

write-host hello world

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

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

write-host hello world

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

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

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

$b = {"write-host hello $a"}.GetNewClosure()
& $b
write-host hello world
$a = "new world"
& $b
write-host hello world

{} 符号表示您可能已经知道的脚本块对象。这可以传递给Invoke-Command,这会打开其他选项。您还可以在脚本块内创建稍后可以传入的参数。请参阅about_Script_Blocks 了解更多信息。

【讨论】:

  • 对不起,是的意思是 $a 而不是 $b,尽管我认为问题仍然存在。更新了问题
  • 这是不正确的,并且错过了问题的关键 - 打印 $b 只打印 write-host "hello $a" 并且问题要求 write-host "hello world"
  • 您是否通读了帖子并尝试了不同的场景?您必须在脚本块内的所有内容周围加上引号才能打印整个文本,这在我的示例中。
  • 我了解,但您已更改问题以将脚本块的内容替换为字符串。相反,问题假设您已经有一个脚本块,并且想要打印其内容而不执行它。
  • 找到了一个简短的答案。只需运行此$executioncontext.invokecommand.expandstring($b)
猜你喜欢
  • 2023-01-13
  • 1970-01-01
  • 2020-06-05
  • 2019-04-06
  • 1970-01-01
  • 1970-01-01
  • 2013-11-19
  • 2022-07-01
  • 2019-01-07
相关资源
最近更新 更多