Forked from RamblingCookieMonster/Test-Pipeline.ps1
Last active
August 29, 2015 14:24
-
-
Save modulexcite/2cfee5bc9785f4c772e1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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