What if / Wat als [Powershell]

PowershellSymbol

One of the best (little known?) features about Powershell is the -WhatIf switch. A script or cmdlet can have parameters, of course, like

param( [string] $foo )

but it can also have switches that are on or off like

param ( [switch] $verbose )

One of the mostly ubiquitous switches is -WhatIf for commands that could “do damage.” For example:

PS> del foo.txt -whatif
What if: Performing operation “Remove File” on Target “C:\foo.txt”.
PS> get-process outlook | stop-process -WhatIf
What if: Performing operation “Stop-Process” on Target “OUTLOOK (2540)”.

Drink in how useful this can be. Fabulous. Anyway, so we wanted to make our own scripts have this ability. Since our scripts are mostly strung together with built-in commands, we want to have a WhatIf switch be inherited by the sub-commands.

Switches are either present or not present so I tried a silly thing like this:

param ( [string] $file, [switch] $WhatIf)
if ($WhatIf.IsPresent) { $WhatIf = “-WhatIf” }
del $file $WhatIf

But this is cleaner:

“You can forward switch params to cmdlet parameters of type switch like so”

param([string]$file, [switch]$WhatIf=$false)
del $file -WhatIf:$whatif

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *