February 13, 2013

How to add –whatif support to a function

 

Function Get-HelloWorld {
    [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact="Low")]
    param()
    $message="Hello world"
    if ($PSCmdlet.ShouldProcess($message,"Write-host")) {
        write-host $message
    }
  }

Get-HelloWorld -whatif will produce :

What if: Performing operation "Write-host" on Target "Hello world".

As a bonus, you will also be able to use the -confirm and –verbose parameter

No comments:

Post a Comment