Home > Microsoft, Powershell > PowerShell: Controlling Cmdlet parameters

PowerShell: Controlling Cmdlet parameters

PowerShell allows for inline parameter control for some of its cmdlet parameters. Based upon commandline and/or inputfile content you might want to turm some of the cmdlet parameters on or off.

For example: scripts manipulating files will often use the Get-ChildItem cmdlet in combination with the -recurse parameter, but not allways the subfolder files are required. Instead off having multiple Get-ChildItem commandlines (each with their own set of parameters) a single line might be possible.

The following examples use the Get-ChildItem cmdlet to show what I mean.

The command in figure below will display all *.tmp files in the current folder and its subfolders.

Get-ChildItem without parameter control

By extending -recurse with :$false recursive lookup will be turned off.

Get-ChildItem with recures lookup turned off

On the otherhand, replacing $false with $true will turn recursive lookup on again.

So using a boolean variable we can turn recursive lookup on or off from within the script (-recurse:$RecurseOnOff). And of course this method also works for other parameters.

Get-ChildItem with multiple controls

And it does get stranger….. in some occasions you can also reverse the default action of a parameter. Hence the following figure.

Reverse parameter action

The 1st command will show all files with exception of the *.tmp files. By appending :$false to -exclude, we turn -exclude into -include as demonstrated by the 2nd command.

This form of parameter manipulation offers a scala of possibilities. Using script parameters to control cmdlet behaviour can both decrease script size and complexity.

Have fun experimenting with this little trick

  1. No comments yet.
  1. No trackbacks yet.