【问题标题】:PowerShell passing function as parameterPowerShell 传递函数作为参数
【发布时间】:2017-12-05 14:45:06
【问题描述】:

我有两个 PS 脚本(1 个主脚本和 1 个作为模块)。

主脚本使用如下代码:

Write-Host "Press Y to continue"
Execute (ConstructSshSessions)

其中Execute 是一个函数,它询问问题以继续并执行函数ConstructSshSessions 中的脚本。如果用户没有输入Y,则主脚本会跳过函数ConstructSshSessions

模块使用如下代码:

Function Execute($function)
{
    $response = read-host
    Write-Host "You typed: $response"
    if ($response -eq "Y")
    {
        $function
    }
    Remove-Variable response
}

当我执行代码 Excecute (ConstructSshSession) 时,它首先运行创建 SSH 会话的脚本,然后要求用户继续。所以这显然不是我的意图,但我没有看到错误。

我希望它询问用户是否可以继续,然后执行作为参数发送到函数 Execute 的脚本。

【问题讨论】:

    标签: powershell parameter-passing


    【解决方案1】:

    我不建议将提示回复与实际阅读回复分开。我也不建议将函数名传递给类似Exec 的调用例程。

    将确认例程包装在一个返回布尔值的函数中,并将该函数作为if 语句的条件调用。

    function ConfirmStep($msg) {
        $title = 'Confirm Step'
    
        $yes = New-Object Management.Automation.Host.ChoiceDescription '&Yes'
        $no  = New-Object Management.Automation.Host.ChoiceDescription '&No'
        $options = [Management.Automation.Host.ChoiceDescription[]]($no, $yes)
        $default = 1  # $yes
    
        [bool]$Host.UI.PromptForChoice($title, $msg, $options, $default)
    }
    
    if (ConfirmStep "Construct SSH sessions?") {
        ConstructSshSessions
    }
    

    【讨论】:

    • 感谢您的回复。听起来像一个可靠的答案。我最近开始编写脚本,你能向初学者解释一下你的代码吗?我不完全理解代码在做什么。
    • 我已经用你的代码弄明白了。非常感谢。这将完美地工作。
    • 您能否向我解释一下为什么您不推荐我的做法,以便我可以从错误中吸取教训?
    • 您在代码的不同部分分发属于一起的内容(提示和读取输入)。那只会混淆你的代码。另外,总是问自己“通过委派函数调用我能得到什么”。如果答案是“什么都没有”(就像在这种情况下):不要这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多