Adding Support For –WhatIf and -Confirm

by Mar 8, 2012

Ever wanted to support the risk mitigation parameters –WhatIf and –Confirm in your functions, too?

Here’s a code template that you can use to play and see how this works. It’s just a few lines of code:

function Check-RiskMitigation {
  [CmdletBinding(SupportsShouldProcess=$True)]
  param()
  ' THIS ALWAYS WORKS'

  if ($PSCmdlet.ShouldProcess("localhost", "Trying to do something real bad")) {
    'I AM DOING SERIOUS STUFF HERE'
  } else {
    'I AM JUST KIDDING...'
  }
  
  ' THIS ALWAYS WORKS'
}

Run this function, then check out how it responds to the parameters –WhatIf and –Confirm:

PS> Check-RiskMitigation
 THIS ALWAYS WORKS
I AM DOING SERIOUS STUFF HERE
 THIS ALWAYS WORKS

PS> Check-RiskMitigation -WhatIf
 THIS ALWAYS WORKS
What if: Performing operation "Trying to do something real bad" on Target "localhost".
I AM JUST KIDDING...
 THIS ALWAYS WORKS

PS> Check-RiskMitigation -Confirm
 THIS ALWAYS WORKS

Confirm
Are you sure you want to perform this action?
Performing operation "Trying to do something real bad" on Target "localhost".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
I AM DOING SERIOUS STUFF HERE
 THIS ALWAYS WORKS

PS> Check-RiskMitigation -Confirm
 THIS ALWAYS WORKS

Confirm
Are you sure you want to perform this action?
Performing operation "Trying to do something real bad" on Target "localhost".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): n
I AM JUST KIDDING...
 THIS ALWAYS WORKS
PS>

Twitter This Tip! ReTweet this Tip!