Implementing the–WHATIF into an Advanced Function in Windows Powershell

So you think you know how to make an Advanced Function.  I thought I did.   Then I started messing about with HANDLE.EXE from Sysinternals and was REALLY getting into automating that baby with Pipelines and whatnot.

It was all working so beautifully UNTIL….

That’s right “Until…” Until I accidentally ended closing ALL the files in the entire O/S with a typo (well most of them!)

It was then I decided that until I got it so you could pass a –whatif properly, I wasn’t sharing my new toy with the world as it would have been a dangerous release indeed.   There is a VERY important reason Mr. Russinovich did NOT release a utility that in ONE LINE would have closed everything on a server.

But thanks to Powershell, we can pull out his Safety net, automate it and bring in a New one.

the Trick with Using the –whatif is enabling “CmdletBinding” in the Advanced Function and Marking “SupportsShouldProcess” as $TRUE

Something like this

Function global:Close-Openfile()

This of course is just the top of a function called “Close-OpenFile” that has the “CmdletBinding” enabled with SupportsShouldProcess.

With this on it’s very simple to use the “-whatif” parameter.  You need only add in a simple line like this in your Process block

if ( $PSCmdlet.ShouldProcess(‘Jibberish’) ) { BlockofCodeToExecuteIfNO-Whatif }

It messed me up the first time.   The $PSCmdlet.ShouldProcess() method returns a Boolean $TRUE if “whatif” is NOT in use.  If it *IS* then it returns a Boolean $FALSE and outputs a statement similar to this where ‘Jibberish’ is replaced with WHATEVER you want in there that makes sense

What if: Performing operation "Close-Openfile" on Target "Jibberish".

Neat eh?   First time I did it, I got the code backwards and closed everything.   But there you go. 

“-whatif” is EASY to implement and the GREATEST feature of Windows Powershell, A live failsafe !

Special Thanks to Kirk “Poshoholic” Munro and Shay Levy for the help in educating me.  An especially big thanks to James Brundage for being a soundboard for other things Smile

The Power of Shell is in all of us. RELEASE IT!

the Energized Tech

Leave a Reply