簡體   English   中英

如何解析 Powershell 腳本塊中的變量

[英]How to resolve variables in a Powershell script block

鑒於我有:

$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 中進行變量替換,則可以使用以下內容:

$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()方法可用於創建上述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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM