[英]How to control the scope of a PowerShell scriptblock
我有一個用PowerShell編寫的函數:
function replace([string] $name,[scriptblock] $action) {
Write-Host "Replacing $name"
$_ = $name
$action.Invoke()
}
並將用作:
$name = "tick"
replace $agentPath\conf\buildAgent.dist.properties {
(cat templates\buildAgent.dist.properties.tpl) `
-replace '@@serverurl@@', 'http:/localhost:8080/teamcity' `
-replace '@@name@@', $name `
> $_
}
但是我發現在scriptblock中,變量$name
被replace
函數中的$name
param覆蓋。
有沒有辦法執行腳本塊,以便只將變量$_
添加到scriptblock的范圍,但沒有其他內容?
您可以在scriptblock中使用$global:
前綴作為$name
變量:
$name = "tick"
replace $agentPath\conf\buildAgent.dist.properties {
(cat templates\buildAgent.dist.properties.tpl) `
-replace '@@serverurl@@', 'http:/localhost:8080/teamcity' `
-replace '@@name@@', $global:name `
> $_
}
我在前面回答說聲稱PowerShell僅適用於虐待狂。 訣竅在於,如果將函數放入模塊中,則局部變量將變為私有,並且不會傳遞給腳本塊。 然后傳入$_
變量你必須跳更多的箍。
gv '_'
得到powershell變量$_
並通過InvokeWithContext
將它傳遞給上下文。
現在我知道的比我想要的更多:|
New-Module {
function replace([string] $name,[scriptblock] $action) {
Write-Host "Replacing $name"
$_ = $name
$action.InvokeWithContext(@{}, (gv '_'))
}
}
和以前一樣
$name = "tick"
replace $agentPath\conf\buildAgent.dist.properties {
(cat templates\buildAgent.dist.properties.tpl) `
-replace '@@serverurl@@', 'http:/localhost:8080/teamcity' `
-replace '@@name@@', $name `
> $_
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.