WhatIf-Support Without Propagation

by Nov 20, 2012

You can enable the -WhatIf and -Confirm parameters in your functions too, and control which parts of your code get skipped if the user specifies -WhatIf or denies execution with -Confirm:

function Test-WhatIf
{
  [CmdletBinding(SupportsShouldProcess=$true)]
  param()

  $really = $PSCmdlet.ShouldProcess($env:computername, 'Do something dangerous')

  if ($really)
  {
    "OK, I am doing it"
  } else {
    "Just kidding..."
  }

} 

Try and run this function as-is, then again with -WhatIf or -Confirm. It works!

However, the parameters get propagated to any other cmdlet that is called directly or indirectly from your function. So if you call some other function or module command, then there may be additional simulation messages coming from there, too.

If you want to disable this, make sure you reset $WhatIfPreference to the parent scope:

$WhatIfPreference = (Get-Variable WhatIfPreference -Scope 1).Value

Now, any command outside your If-clauses will always execute.

Twitter This Tip! ReTweet this Tip!