如何以编程方式了解传递给 cmdlet 的所有参数

本文关键字:cmdlet 参数 编程 方式 了解 | 更新日期: 2023-09-27 18:34:19

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

My-Cmdlet -foo -bar -foobar

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

看起来在脚本中我们可以使用以下方法做到这一点:$PSBoundParameters.ContainsKey('WhatIf')

我需要与 .net (c#) 中的相同值

如何以编程方式了解传递给 cmdlet 的所有参数

据我所知:$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());
        }
    }
}

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

呵巴特克

在我的头顶上,你不能不访问代码,除非你在 cmdlet 周围创建一个代理命令(用函数包装命令)并向其中添加自定义代码。另一个想法是检查控制台历史记录中上次执行的命令或类似方法。

有些这样。whatifppreferences的GetVariable总是返回false。

我通过使用MyinVocation.buildParameters Dictionary来解决这个问题。

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

问候空想家