Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix ShouldProcess examples
  • Loading branch information
masaru-iritani authored Jan 23, 2022
commit a4cc15c2b729714b2d62692c4b872128331c65b8
61 changes: 29 additions & 32 deletions docs/Rules/ShouldProcess.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
description: Should Process
ms.custom: PSSA v1.20.0
ms.date: 10/18/2021
ms.date: 01/23/2022
ms.topic: reference
title: ShouldProcess
---
Expand All @@ -14,55 +14,52 @@ title: ShouldProcess
If a cmdlet declares the `SupportsShouldProcess` attribute, then it should also call
`ShouldProcess`. A violation is any function which either declares `SupportsShouldProcess` attribute
but makes no calls to `ShouldProcess` or it calls `ShouldProcess` but does not declare
`SupportsShouldProcess`
`SupportsShouldProcess`.

For more information, please refer to `about_Functions_Advanced_Methods` and
`about_Functions_CmdletBindingAttribute`
`about_Functions_CmdletBindingAttribute`.

## How

To fix a violation of this rule, please call `ShouldProcess` method when a cmdlet declares
`SupportsShouldProcess` attribute. Or please add `SupportsShouldProcess` attribute argument when
calling `ShouldProcess`
calling `ShouldProcess`.

## Example

### Wrong

```powershell
function Set-File
{
[CmdletBinding(SupportsShouldProcess=$true)]
Param
(
# Path to file
[Parameter(Mandatory=$true)]
$Path
)
"String" | Out-File -FilePath $FilePath
}
function Set-File
{
[CmdletBinding(SupportsShouldProcess=$true)]
Param
(
# Path to file
[Parameter(Mandatory=$true)]
$Path
)

"String" | Out-File -FilePath $Path
}
```

### Correct

```powershell
function Set-File
{
[CmdletBinding(SupportsShouldProcess=$true)]
Param
(
# Path to file
[Parameter(Mandatory=$true)]
$Path
)
function Set-File
{
[CmdletBinding(SupportsShouldProcess=$true)]
Param
(
# Path to file
[Parameter(Mandatory=$true)]
$Path
)

if ($PSCmdlet.ShouldProcess("Target", "Operation"))
{
"String" | Out-File -FilePath $FilePath
}
else
{
Write-Host ('Write "String" to file {0}' -f $FilePath)
}
if ($PSCmdlet.ShouldProcess($Path, "Write"))
{
"String" | Out-File -FilePath $Path
}
}
```