Tuesday, July 31, 2012

What If Mode - Adding WhatIf to Scripts

What if mode is one of my favorite features of PowerShell.  No other language I have used has given me this ability, and it is very exciting and useful.  You probably already know that -WhatIf will describe the action that would take place rather than actually doing it.  How then can one use it in a script?  It takes a few steps.


First, add the code [CmdletBinding(SupportsShouldProcess=$true)] immediately before the Param statement. This unlocks -Whatif and other common parameters.  Next, wherever you are going to perform an operation that would change something, such as to move an AD account, enclose the commands(s) in an if statement with a condition like this:

if ($PScmdlet.ShouldProcess("Move Account $($child.cn.toString()) to OU $($disabledOU.ou.toString())","","")) {
    $child.MoveTo($disabledOU)
}


The $PSCmdlet.ShouldProcess() method takes many arguments, but the one I use the most takes first a string describing the action and the object, followed by two empty strings.  The execution of this method will respond appropriately based on whether WhatIf is on or not.


There is a lot of potential here, and I encourage you to explore it!

No comments:

Post a Comment