수색…


통사론

  • $ PSCmdlet.ShouldProcess ( "대상")
  • $ PSCmdlet.ShouldProcess ( "대상", "작업")

매개 변수

매개 변수 세부
목표 자원이 변경되고 있습니다.
동작 수행중인 작업입니다. 기본값은 cmdlet의 이름입니다.

비고

$PSCmdlet.ShouldProcess() 는 자동으로 자세한 출력에 메시지를 씁니다.

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

추가 - cmdlet에 대한 지원 및 확인 지원

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

인수 하나를 사용하여 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