【问题标题】:How to control the scope of a PowerShell scriptblock如何控制 PowerShell 脚本块的范围
【发布时间】:2017-10-01 01:42:35
【问题描述】:

我有一个用 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 `
        > $_
}

但是我发现在脚本块中,变量$namereplace 函数中的$name 参数覆盖。

有没有办法执行脚本块,以便只有变量$_ 被添加到脚本块的范围内,而没有其他内容?

【问题讨论】:

    标签: powershell closures scriptblock


    【解决方案1】:

    您可以将$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 `
            > $_
    }
    

    【讨论】:

    • 我可以,但那是要求我或其他开发人员有一天忘记并且将来会随机出现问题。我希望在脚本块的调用者礼貌并且不会将所有局部变量注入范围的另一端有某种解决方案。
    • 我找到了一种方法。这肯定很丑:) 看看我的回答。
    • 它看起来很难看,但我同意它对其他开发人员使用该功能更好。
    【解决方案2】:

    我声称 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 `
            > $_
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-17
      • 1970-01-01
      • 2012-01-21
      • 2021-12-19
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多