【问题标题】:Is there a way how to use [switch] parameter in Azure Runbook有没有办法在 Azure Runbook 中使用 [switch] 参数
【发布时间】:2017-10-18 10:59:37
【问题描述】:

我有一个小脚本,我将作为 Azure Runbook 迁移到 Azure 自动化帐户。 最初,该脚本使用了一些开关参数,例如 -WhatIf。

#Requires -Version 3.0 
[cmdletbinding()]
param(
 #//Other parameters
[switch]$WhatIf
 #//Other parameters
)
if ($WhatIf.IsPresent) {
 #////Do something
}

但是当我尝试在测试窗格中对其进行测试时,我无法将任何值传递给它。

我尝试了 1,0, $True, $true, True, False 但似乎没有任何效果。我知道我可以更改参数的类型,但我想知道可能有更好的方法。有吗?

【问题讨论】:

    标签: powershell azure


    【解决方案1】:

    只需指定值 truefalse 不带任何单/双引号或任何其他修饰。它可以在 AA Runbooks 中正常工作。在网上找不到相同的指导后,我自己发现了它。

    但是,就像@AndyHerb 提到的那样,最佳做法是在 AA Runbook 中使用 bool 类型而不是 switch,因为它使事情变得更容易。

    HTH...

    【讨论】:

    • "true" 和 "false" 必须小写也没什么用。非常感谢!
    【解决方案2】:

    虽然您可以在 Azure 自动化运行手册中使用 Switch 参数,但最佳实践建议是改用 [bool]。您可以将其默认为 false,甚至可以检查它是否已被传入(如果您出于任何原因想要/需要)。这将使您的函数如下所示:

    #Requires -Version 3.0 
    [CmdletBinding()]
    param (
        [Parameter (Mandatory = $false)]
        [bool]$WhatIf
    )
    
    # Check if user supplied $WhatIf parameter
    if ($PSBoundParameters.ContainsKey('WhatIf')) {
        # User specified -WhatIf
    } else {
        # User did not specify -WhatIf
    }
    
    # Simple parameter check - can't differentiate between $false supplied by user and parameter not supplied
    if ($WhatIf) {
        # User specified -WhatIf
    } else {
        # User did not specify -WhatIf
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 2011-01-03
      • 2022-01-07
      相关资源
      最近更新 更多