Google

2014-02-10

PowerShell WhatIf

There are tons of resources on the web on how to use -whatif parameter in Powershell functions. I won't go over them but here is a mistake I noticed people sometimes do: They forget to add SupportsShouldProcess to the main script.




Couple of things to note here:

* When you pass -whatif parameter to the main script, it gets passed down to any 'advanced' function that is also supporting whatif.

In out example, Test-WhatifTraversing function support -whatif, because it too has the following line

[CMDLETBINDING(SupportsShouldProcess)]

* Once you use -whatif to call your script, it will not only pass it to Advanced Functions, but it will automatically execute on any other native PowerShell cmdlets that supports -whatif

* You want to wrap the 'dangerous code' you have in that 'If' block so that when you pass -whatif it does NOT execute, but even if you don't have any such code, it is still beneficial to add 'SupportsShouldProcess' to all your functions and scripts because of what I mentioned above.
Post a Comment