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
    }
}