サーチ…


構文

  • $ PSCmdlet.ShouldProcess( "Target")
  • $ PSCmdlet.ShouldProcess( "Target"、 "Action")

パラメーター

パラメータ詳細
ターゲットリソースが変更されています。
アクション実行されている操作。デフォルトはコマンドレットの名前です。

備考

$PSCmdlet.ShouldProcess()は自動的に冗長出力にメッセージを書き込みます。

PS> Invoke-MyCmdlet -Verbose
VERBOSE: Performing the operation "Invoke-MyCmdlet" on target "Target of action"

コマンドレットに-WhatIfと-Confirmのサポートを追加する

function Invoke-MyCmdlet {
    [CmdletBinding(SupportsShouldProcess = $true)]
    param()
    # ...
}

1つの引数で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"):

完全な使用例

他の例では、条件付きロジックをトリガする方法を私に明確に説明できませんでした。

この例では、基になるコマンドも-Confirmフラグを聴いています。

<#
Restart-Win32Computer
#>

function Restart-Win32Computer 
{
    [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact="High")]
    param (
    [parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
    [string[]]$computerName,
    [parameter(Mandatory=$true)]
    [string][ValidateSet("Restart","LogOff","Shutdown","PowerOff")] $action,
    [boolean]$force = $false
)
BEGIN {
# translate action to numeric value required by the method
switch($action) {
    "Restart"
    {
        $_action = 2
        break
    }
    "LogOff"
    {
        $_action = 0
        break
    }
    "Shutdown"
    {
        $_action = 2
        break
    }
    "PowerOff"
    {
        $_action = 8
        break
    }
}
# to force, add 4 to the value
if($force) 
{
    $_action += 4
}
write-verbose "Action set to $action"
}
PROCESS {
    write-verbose "Attempting to connect to $computername"
    # this is how we support -whatif and -confirm
    # which are enabled by the SupportsShouldProcess
    # parameter in the cmdlet bindnig
    if($pscmdlet.ShouldProcess($computername)) {
        get-wmiobject win32_operatingsystem -computername $computername | invoke-wmimethod -name Win32Shutdown -argumentlist $_action
    }
}
} 
#Usage:
#This will only output a description of the actions that this command would execute if -WhatIf is removed.
'localhost','server1'| Restart-Win32Computer -action LogOff -whatif 

#This will request the permission of the caller to continue with this item.
#Attention: in this example you will get two confirmation request because all cmdlets called by this cmdlet that also support ShouldProcess, will ask for their own confirmations...
'localhost','server1'| Restart-Win32Computer -action LogOff -Confirm


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow