1
1
---
2
2
description : Should Process
3
3
ms.custom : PSSA v1.20.0
4
- ms.date : 10/18/2021
4
+ ms.date : 03/24/2022
5
5
ms.topic : reference
6
6
title : ShouldProcess
7
7
---
@@ -16,8 +16,11 @@ If a cmdlet declares the `SupportsShouldProcess` attribute, then it should also
16
16
but makes no calls to ` ShouldProcess ` or it calls ` ShouldProcess ` but does not declare
17
17
` SupportsShouldProcess `
18
18
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 )
21
24
22
25
## How
23
26
@@ -30,39 +33,43 @@ calling `ShouldProcess`
30
33
### Wrong
31
34
32
35
``` 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
+ }
44
47
```
45
48
46
49
### Correct
47
50
48
51
``` 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,
58
60
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
67
73
}
74
+ }
68
75
```
0 commit comments