PoshCode Archive  Artifact [954dc3dc7a]

Artifact 954dc3dc7a571b345a313617317415b1b51df78c1c73b27a394afdbb012caef1:

  • File Demo-Pipepline.ps1 — part of check-in [f41e4709f1] at 2018-06-10 14:04:28 on branch trunk — Just a simple learning tool … (user: Joel Bennett size: 2203)

# encoding: ascii
# api: powershell
# title: Demo-Pipepline
# description: Just a simple learning tool … 
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# function: Demo-Pipeline
# x-poshcode-id: 5939
# x-archived: 2016-08-26T03:52:22
# x-published: 2016-07-16T19:19:00
#
# Made InputObject optional, so you can call it without any pipeline input
#
function Demo-Pipeline {
   #.Synopsis
   #    Useful for demonstrating how pipeline output works
   #.Example
   #    1..3 | Demo-Pipeline Red | Demo-Pipeline Green -OutputFromBegin | Demo-Pipeline Blue
   [CmdletBinding()]
   param (
      [Parameter(Position=0)]
      [ConsoleColor]$Color,

      [Parameter(Position=1,ValueFromPipeline=$true)]
      [String[]]$InputObject,

      [Switch]$OutputFromBegin,

      [Switch]$OutputFromEnd
   )
   begin {
      Write-Verbose "ENTER Begin $Color"
      if ($PSBoundParameters.ContainsKey("InputObject")) {
         Write-Warning "We don't process InputObject in begin, because that wouldn't be PowerShelly"
      }

      Write-Host "BEGIN ($Color)" -Foreground $Color

      $HasOutput = $false
      
      if($OutputFromBegin) {
         $HasOutput = $true
         Write-Output "$Color BEGIN OUTPUT"
      }


      Write-Verbose "EXIT Begin $Color"
   }
   process {
      Write-Verbose "ENTER Process $Color"
      # This happens for each item that comes through:
      Write-Host "PROCESS: $InputObject ($Color)" -Fore $Color

      # We pass through the InputObject for the next guy
      Write-Output $InputObject

      # We _add_ one output thing of our own..
      if(!$HasOutput -and !$OutputFromEnd) {
         $HasOutput = $true
         Write-Output "$Color PROCESS OUTPUT"
      }

      Write-Verbose "EXIT Process $Color"
   }
   end {
      Write-Verbose "ENTER End $Color"

      # This happens just once, at the end (notice the last input object is still around):
      Write-Host "END: $InputObject ($Color)" -Fore $Color

      if($OutputFromEnd) {
         $HasOutput = $true
         Write-Output "$Color END OUTPUT"
      }

      Write-Verbose "EXIT End $Color"
   }
}