Saturday, February 4, 2012

SwitchParameter


I was curious how one can create his own cmdlet, with parameters which do not take values.
For example, when a Cmdlet runs, we can specify -Verbose. This parameter does not take a value, it simply exists.

We do this by creating a parameter like this.

    private SwitchParameter hasHeader;
    [Parameter(Position = 1,
    Mandatory = false,
    ValueFromPipelineByPropertyName = true,
    HelpMessage = "Whether first row is a header"),
    ValidateNotNullOrEmpty()]
    public SwitchParameter HasHeader { 
              get { return hasHeader; } 
              set { hasHeader = value; }
      }

And then we check for it like this:

if (HasHeader.IsPresent){ };

It is important to note that the default value is false.

1 comment:

Jeremy said...

Just what I was looking for!