【问题标题】:How to know whether parameter "whatif" has been passed to a customer cmdlet programmatically?如何知道参数“whatif”是否已以编程方式传递给客户 cmdlet?
【发布时间】:2012-05-24 09:50:40
【问题描述】:

我想知道 whatif 参数是否已传递给 cmdlet。

例如:remove-mycmdlet -whatif

我试图通过查找变量的值来做到这一点:WhatIfPreference

但它总是产生错误。

请问如何知道whatif参数是否传入?

非常感谢,

问候, 纳雷什

【问题讨论】:

    标签: c# .net powershell powershell-2.0 cmdlets


    【解决方案1】:

    当我这样定义函数时:

    function Test-WhatIf {
    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
    )
    
        $WhatIfPreference
        $PSBoundParameters.ContainsKey('WhatIf')
    }
    

    我得到 $false 或 $true,这取决于在命令中添加 -WhatIf。 虽然这只是高级功能,但我不希望在编译命令中出现不同的行为...您确定您已正确实现 SupportsShouldProcess 吗?

    【讨论】:

    • 非常感谢您的快速回复。这是我在 .net (c#) 中实现的自定义 cmdlet。我怎样才能以编程方式做到这一点?基本上我使用了“PSCmdlet 的对象 GetVariableValue(字符串名称)”。它总是返回假。顺便说一句,c# 中是否有任何等价的 $PSBoundParameters.ContainsKey('WhatIf') ?
    • 是的,我实现了 supportshouldprocess 正确,因为确认/whatif 参数在用户传递它们时按预期工作。我声明了我的 cmdlet 并设置了以下属性: [Cmdlet(VerbsCommon.Remove, "EmcLun", SupportsShouldProcess=true, ConfirmImpact=ConfirmImpact.High)] 只是我需要知道用户已通过这些参数,但不知道该怎么做它以编程方式在 .net 中。
    • 好的,抓起 VS 并尝试在“正确的”cmdlet 中找到相同的内容。您将在第二个线程上找到我的答案... :)
    猜你喜欢
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 2015-10-24
    • 2023-04-07
    • 1970-01-01
    • 2017-12-28
    相关资源
    最近更新 更多