NNP
NNP

Reputation: 3451

How to know all the parameters passed to a cmdlet programmatically?

I have customer cmdlet implemented in .net. I would like to know all the parameters user passed to it.

My-Cmdlet -foo -bar -foobar

Basically i would like to know that user executed this cmdlet with parameter foo, bar, foobar programmatically.

Looks like in script we can do it using: $PSBoundParameters.ContainsKey('WhatIf')

I need equalent of that in .net (c#)

Upvotes: 1

Views: 1662

Answers (3)

NNP
NNP

Reputation: 3451

Some how this.GetVariable for whatifpreference always returned false.

i worked around this by using 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(); 
    }
}

Regards, Dreamer

Upvotes: 0

BartekB
BartekB

Reputation: 8650

As far as I remember: $PSBoundParameters is just shortcut for $MyInvocation.BoundParameters: $MyInvocation.BoundParameters.Equals($PSBoundParameters) True

If you want to get the same information in cmdlet that you wrote, you can get it like that...:

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());
        }
    }
}

The code is quick'n'dirty, but you should get the picture. Disclaimer: I'm not a developer, so I'm probably doing it wrong. ;)

HTH Bartek

Upvotes: 7

Shay Levy
Shay Levy

Reputation: 126852

Off the top of my head, you can't without having access to the code, unless you create a proxy command around the cmdlet (wrap the command with a function) and add your custom code to it. Another idea would be to check the last executed command in the console history or a similar method.

Upvotes: 0

Related Questions