Book Image

PowerShell Troubleshooting Guide

By : Mike Shepard
Book Image

PowerShell Troubleshooting Guide

By: Mike Shepard

Overview of this book

Table of Contents (15 chapters)
PowerShell Troubleshooting Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

SupportsShouldProcess


Cmdlets whose execution changes the state of the system where some risk is involved should include risk mitigation parameters, which are the following:

  • -WhatIf

  • -Confirm

For an advanced function to use these parameters, the SupportsShouldProcess parameter of the CmdletBinding attribute should be given a value of $true. Portions of code that involve the risk should be guarded with the $PSCmdlet.ShouldProcess() method. This method returns $true unless the caller specified the –WhatIf switch or the –Confirm switch followed by a negative response:

function remove-something{
[CmdletBinding(SupportsShouldProcess=$true)]
Param($item)

    if ($PSCmdlet.ShouldProcess($item)){
       Write-Output "Removing $item"
    }

}

Here is some sample output from that advanced function showing the operation of the –Whatif and –Confirm switches:

Parameter name validation

One important consequence of writing advanced functions (that is, using CmdletBinding) is that named parameters that are...