Determine Pipeline Input
There was a recent post on the Powershell Forums titled Finding Function Name in which the user wanted to know if there was anyway to determine which cmdlet or function was being used to send input down the pipeline. In order to assist I first needed to do some research as I was unsure how to make this determination. It just so happened that the first response was by Kazun (PS MVP..enough said.. ) and he suggested using $MyInvocation.Line.
So upon doing a google search I came across the following article PowerShell Deep Dive: Using $MyInvocation by Kirk Munro which went into great detail on how to use the $MyInvocation variable to make a similiar distinction. From that article I came up with the following script to demo $MyInvocation. It includes 4 functions. The one that anaylzes the pipeline input is Out-Name. Here is the script…
Function Get-Svc { Get-Service | select -First 2 } Function Get-Proc { Get-Process | Select -First 2 } Function Get-File { GCI c:\ | Select -First 2 } Function Out-Name { param($name) Begin { $global:Invocation = $MyInvocation.line } Process{ if( $global:Invocation -match "Get-Svc" ) { $_.name } Elseif ( $global:Invocation -match "Get-Proc" ) { $_.vm } Else { Write-Host "Get-Svc was not used" } } } Get-Svc | out-Name #Get-Proc | out-name #Get-File | Out-Name
The script was created soley to demo $MyInvocation but could be altered (as with any script) to make it fit your needs.