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

  1.  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:

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

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.