Created
December 29, 2014 15:07
-
-
Save RamblingCookieMonster/558007250a0380b94ac4 to your computer and use it in GitHub Desktop.
Pipeline and ShouldProcess demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
This function and following examples illustrate the implementation of two helpful scenarios: | |
Pipeline input, with verbose output describing the values and types within the Begin, Process, and End blocks | |
ShouldProcess support, with friendly bypass handling using a Force switch. | |
#> | |
Function Test-Pipeline { | |
[cmdletbinding(SupportsShouldProcess=$true, ConfirmImpact="Medium")] | |
param( | |
[parameter( Mandatory = $false, | |
ValueFromPipeline = $True, | |
ValueFromPipelineByPropertyName = $True)] | |
[string[]]$ComputerName = "$env:computername", | |
[switch]$Force | |
) | |
Begin | |
{ | |
$RejectAll = $false | |
$ConfirmAll = $false | |
Write-Verbose "BEGIN Block - `$ComputerName is a $(try{$ComputerName.GetType()} catch{$null}) with value $ComputerName`nPSBoundParameters is `t$($PSBoundParameters |Format-Table -AutoSize | out-string )" | |
} | |
Process | |
{ | |
Write-Verbose "PROCESS Block - `$ComputerName is a $(try{$ComputerName.GetType()} catch{$null}) with value $ComputerName`nPSBoundParameters is `t$($PSBoundParameters |Format-Table -AutoSize | out-string )" | |
foreach($Computer in $ComputerName) | |
{ | |
if($PSCmdlet.ShouldProcess( "Processed the computer '$Computer'", | |
"Process the computer '$Computer'?", | |
"Processing computer" )) | |
{ | |
if($Force -Or $PSCmdlet.ShouldContinue("Are you REALLY sure you want to process '$Computer'?", "Processing '$Computer'", [ref]$ConfirmAll, [ref]$RejectAll)) { | |
Write-Verbose "----`tPROCESS Block, FOREACH LOOP - processed item is a $(try{$computer.GetType()} catch{$null}) with value $computer`nPSBoundParameters is `t$($PSBoundParameters |Format-Table -AutoSize | out-string )" | |
} | |
} | |
} | |
} | |
End | |
{ | |
Write-Verbose "END Block - `$ComputerName is a $(try{$ComputerName.GetType()} catch{$null}) with value $ComputerName`nPSBoundParameters is `t$($PSBoundParameters |Format-Table -AutoSize | out-string )" | |
} | |
} | |
#Define some computer names we will test with | |
$Computers = "Computer1", "Computer2" | |
# Test this using pipeline input | |
$Computers | Test-Pipeline -verbose | |
#Test this using named parameters | |
Test-Pipeline -ComputerName $Computers -Verbose | |
#Test this using force with named parameters | |
Test-Pipeline -ComputerName $Computers -Force -Verbose | |
#ShouldProcess implementation borrowed from Jaykul's Demo-ShouldProcess - http://poshcode.org/3291 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment