58. Using ShouldProcess¶
Note
The below information is extensively based in information taken from the PowerShell® Notes for Professionals book. I plan to extend this information based on my day to day usage of the language.
1 2 3 | Parameter Details Target The resource being changed. Action The operation being performed. Defaults to the name of the cmdlet. |
58.1: Full Usage Example¶
Other examples couldn't clearly explain to me how to trigger the conditional logic.
This example also shows that underlying commands will also listen to the -Confirm flag!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | <# 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 -Message "Action set to $action" } PROCESS { Write-Verbose -Message "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 -Class 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 |
58.2: Adding -WhatIf and -Confirm support to your cmdlet¶
1 2 3 4 5 | function Invoke-MyCmdlet { [CmdletBinding(SupportsShouldProcess = $true)] param() # ... } |
58.3: Using ShouldProcess() with one argument¶
1 2 3 | if ($PSCmdlet.ShouldProcess("Target of action")) { # Do the thing } |
When using -WhatIf :
What if: Performing the action "Invoke-MyCmdlet" on target "Target of action"
When using -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"):