Scott Hanselman

WhatIf Powershell

August 04, 2006 Comment on this post [0] Posted in PowerShell
Sponsored By

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 was reminded by Keith Hill that this was cleaner:

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

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

"Bruce Payette and I had a newsgroup exchange on this a while back and he mentioned that they made sure you could still pass a "value" to a switch parameter for this very reason. I don't know of any other ways to make this better though."

Thanks Keith!

Technorati :
Del.icio.us :

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.