11---
22description : Should Process
33ms.custom : PSSA v1.20.0
4- ms.date : 10/18/2021
4+ ms.date : 03/24/2022
55ms.topic : reference
66title : ShouldProcess
77---
@@ -16,8 +16,11 @@ If a cmdlet declares the `SupportsShouldProcess` attribute, then it should also
1616but makes no calls to ` ShouldProcess ` or it calls ` ShouldProcess ` but does not declare
1717` SupportsShouldProcess `
1818
19- For more information, please refer to ` about_Functions_Advanced_Methods ` and
20- ` about_Functions_CmdletBindingAttribute `
19+ For more information, see the following articles:
20+
21+ - [ about_Functions_Advanced_Methods] ( /powershell/modules/microsoft.powershell.core/about/about_Functions_Advanced_Methods )
22+ - [ about_Functions_CmdletBindingAttribute] ( /powershell/modules/microsoft.powershell.core/about/about_Functions_CmdletBindingAttribute )
23+ - [ Everything you wanted to know about ShouldProcess] ( /powershell/scripting/learn/deep-dives/everything-about-shouldprocess )
2124
2225## How
2326
@@ -30,39 +33,43 @@ calling `ShouldProcess`
3033### Wrong
3134
3235``` powershell
33- function Set-File
34- {
35- [CmdletBinding(SupportsShouldProcess=$true)]
36- Param
37- (
38- # Path to file
39- [Parameter(Mandatory=$true)]
40- $Path
41- )
42- "String" | Out-File -FilePath $FilePath
43- }
36+ function Set-File
37+ {
38+ [CmdletBinding(SupportsShouldProcess=$true)]
39+ Param
40+ (
41+ # Path to file
42+ [Parameter(Mandatory=$true)]
43+ $Path
44+ )
45+ "String" | Out-File -FilePath $Path
46+ }
4447```
4548
4649### Correct
4750
4851``` powershell
49- function Set-File
50- {
51- [CmdletBinding(SupportsShouldProcess=$true)]
52- Param
53- (
54- # Path to file
55- [Parameter(Mandatory=$true)]
56- $Path
57- )
52+ function Set-File
53+ {
54+ [CmdletBinding(SupportsShouldProcess=$true)]
55+ Param
56+ (
57+ # Path to file
58+ [Parameter(Mandatory=$true)]
59+ $Path,
5860
59- if ($PSCmdlet.ShouldProcess("Target", "Operation"))
60- {
61- "String" | Out-File -FilePath $FilePath
62- }
63- else
64- {
65- Write-Host ('Write "String" to file {0}' -f $FilePath)
66- }
61+ [Parameter(Mandatory=$true)]
62+ [string]$Content
63+ )
64+
65+ if ($PSCmdlet.ShouldProcess($Path, ("Setting content to '{0}'" -f $Content)))
66+ {
67+ $Content | Out-File -FilePath $Path
68+ }
69+ else
70+ {
71+ # Code that should be processed if doing a WhatIf operation
72+ # Must NOT change anything outside of the function / script
6773 }
74+ }
6875```
0 commit comments