Weekend Scripter: Easily Add Whatif Support to Your PowerShell Functions
Summary: Microsoft Scripting Guy, Ed Wilson, shows how to easily add whatif support to your Windows PowerShell functions.
Microsoft Scripting Guy, Ed Wilson, is here. I love demoing Windows PowerShell to people who have never seen it—and believe it or not, there are still IT Pros who have not seen or used Windows PowerShell. Most people have heard of it by now (if they are in the business), but there is still a surprisingly large number of people who do not use Windows PowerShell. One of the features that generally gets ooohs and ahhhhs (and at times even applause) is the whatif parameter.
I generally tell people that they no longer have to run a command to see what it will do. Often I ask for a show of hands to see how many people have run a command and they did not know what it would do. Not surprisingly, the number of hands that goes up is large. Scarier, is when I ask who has run a command on a production system, and they were not certain what it would do. This is not a sign of carelessness, but rather a sign of desperation—the server is down, you go to TechNet, and it says to fix the problem, run this cryptic command. You do it and hope for the best. But what if there was a type-o on that page? With Windows PowerShell, this is no longer a concern because you can use whatif.
Adding support for the whatif parameter
One of the great features of Windows PowerShell is using the whatif parameter on cmdlets that change the system state, such as the Stop-Service or the Stop-Process cmdlets. In fact, by consistently utilizing the whatif switched parameter, it is possible to avoid many inadvertent system outages. As a Windows PowerShell best practice, you should also implement the whatif parameter in your advanced functions. In the past, this meant creating special parameters, and adding lots of extra code to handle the output. Now, it requires a single line of code.
Note [cmdletbinding()] appears with empty parentheses because there are other things, such as SupportsShouldProcess, that can appear between the parentheses.
The following function illustrates setting SupportsShouldProcess to True inside the parentheses of the cmdletbinding attribute.
Now when you call the function with the whatif switched parameter, a message appears in the output detailing the exact behavior the cmdlet takes when run without the whatif parameter. This is shown in the image that follows.
I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at email@example.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
Thanks, now I am going back over all my scripts and replacing my ‘[switch]$Test’ parameter 🙂
I sure appreciate all of your posts, Ed!