ShouldProcess

严重性级别:警告

默认状态:始终启用

Description

该规则用于检测声明与SupportsShouldProcess叫注之间的ShouldProcess不匹配。 当 cmdlet 声明属性时 SupportsShouldProcess ,也应调用该 ShouldProcess 方法。

违规发生在以下情况:

  • 函数声明 SupportsShouldProcess 但不调用 ShouldProcess
  • 函数 ShouldProcess 调用但不声明 SupportsShouldProcess

为解决此违规,确保 ShouldProcess 调用与 SupportsShouldProcess 属性声明配对。

如需了解更多信息,请参阅以下文章:

Example

非符合性

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

合规的

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

        [Parameter(Mandatory=$true)]
        [string]$Content
    )

    if ($PSCmdlet.ShouldProcess($Path, ("Setting content to '{0}'" -f $Content)))
    {
        $Content | Out-File -FilePath $Path
    }
    else
    {
        # Code that should be processed if doing a WhatIf operation
        # Must NOT change anything outside of the function / script
    }
}

配置规则

这个规则始终是启用的,不能配置。 请采用以下方法之一以避免使用此规则:

  • 创建一个自定义规则配置文件,只包含你想要的规则,或者排除你不想要的规则。
  • 在代码中添加相应的规则抑制属性,以抑制特定代码块的规则。 更多信息请参见使用 PSScriptAnalyzer 中的“抑制规则”部分。