使用带有一个参数的 ShouldProcess()

if ($PSCmdlet.ShouldProcess("Target of action")) {
    # Do the thing
}

使用 -WhatIf 时:

What if: Performing the action "Invoke-MyCmdlet" on target "Target of action"

使用 -Confirm 时:

Are you sure you want to perform this action?
Performing operation "Invoke-MyCmdlet" on target "Target of action"
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):