【问题标题】:How to know all the parameters passed to a cmdlet programmatically?如何知道以编程方式传递给 cmdlet 的所有参数?
【发布时间】:2012-05-24 10:21:47
【问题描述】:

我在 .net 中实现了客户 cmdlet。我想知道用户传递给它的所有参数。

My-Cmdlet -foo -bar -foobar

基本上我想知道用户以编程方式使用参数 foo、bar、foobar 执行了这个 cmdlet。

看起来我们可以在脚本中使用:$PSBoundParameters.ContainsKey('WhatIf')

我需要 .net (c#) 中的等价物

【问题讨论】:

    标签: c# powershell powershell-2.0 cmdlets cmdlet


    【解决方案1】:

    据我所知:$PSBoundParameters 只是 $MyInvocation.BoundParameters 的快捷方式: $MyInvocation.BoundParameters.Equals($PSBoundParameters) 是的

    如果您想在 编写的 cmdlet 中获取相同的信息,您可以这样获取...:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Management.Automation;
    
    namespace Test
    {
        [Cmdlet(VerbsCommon.Get, "WhatIf", SupportsShouldProcess = true)]
        public class GetWhatIf : PSCmdlet
        {
    
            // Methods
            protected override void BeginProcessing()
            {
                this.WriteObject(this.MyInvocation.BoundParameters.ContainsKey("WhatIf").ToString());
            }
        }
    }
    

    代码是快速的'n'dirty,但你应该得到图片。免责声明:我不是开发人员,所以我可能做错了。 ;)

    HTH 巴特克

    【讨论】:

    • 还需要考虑InvocationInfo.UnboundParameters 用于未绑定到参数的任何参数(例如,当有参数具有ValueFromRemainingArguments true 时)。
    【解决方案2】:

    在我的脑海中,你不能不访问代码,除非你围绕 cmdlet 创建一个代理命令(用函数包装命令)并将你的自定义代码添加到它。另一个想法是检查控制台历史记录中最后执行的命令或类似方法。

    【讨论】:

      【解决方案3】:

      whatifpreference 的 this.GetVariable 总是返回 false 的一些原因。

      我使用 myinvocation.buildparameters 字典解决了这个问题。

      public bool WhatIf
      {
          get
          {                                
              //if (this.GetVaribaleValue<bool>("WhatIfPreference", out whatif))
              return this.MyInvocation.BoundParameters.ContainsKey("WhatIf")
                  && ((SwitchParameter)MyInvocation.BoundParameters["WhatIf"]).ToBool(); 
          }
      }
      

      问候, 梦想家

      【讨论】:

        猜你喜欢
        • 2012-05-24
        • 2015-10-24
        • 2023-04-07
        • 1970-01-01
        • 2017-12-28
        • 1970-01-01
        • 2014-12-08
        • 1970-01-01
        • 2014-11-09
        相关资源
        最近更新 更多