Q. How do I make a PowerShell function support ShouldProcess?

To support support ShouldProcess, your function must include the [CmdletBinding(SupportsShouldProcess=$true)] attribute.

Don Jones

June 14, 2010

1 Min Read
blue abstract shell on white background

Q. How do I make a PowerShell function support ShouldProcess?

A. To support support ShouldProcess, your function must include the [CmdletBinding(SupportsShouldProcess=$true)] attribute. Run

 help about_functions_advanced

for more information on this attribute. Then, locate the code in your function that will change the system in some way, such as rebooting it. Wrap that code in a condition statement:

If ($pscmdlet.ShouldProcess($target)) {# your commands here}

The $target variable should contain the name of whatever you're modifying, such as a computer name or process name. The shell will handle it from there. If you include comment-based help for your function, there's no need to specify the -whatif and -confirm parameters. Declaring support for ShouldProcess will cause the shell to automatically recognize -whatif and -confirm.

Do you have a Windows PowerShell question? Find more PowerShell FAQs, articles, and other resources at windowsitpro.com/go/DonJonesPowerShell.

 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like