Pipeline Used Or Not?

by Mar 14, 2012

Sometimes you may want to know if your function received parameters over the pipeline or direct. Here is a way to find out:

function test {
  [CmdletBinding(DefaultParameterSetName='NonPipeline')]
  param(
    [Parameter(ValueFromPipeline=$true)]
    $Data
  )
  
  begin { $direct = $PSBoundParameters.ContainsKey('Data') }

  process {}
  
  end { $pipeline = $PSBoundParameters.ContainsKey('Data') -and -not $direct 
    "Direct? $direct"
    "Pipeline? $pipeline"
  }
}

This function has one parameter called –Data that accepts input both via pipeline and directly. To find out where the input came from, you can check whether there was input in the begin block – which is before the pipeline started. If so, the data came from a direct assignment:

PS> 1..10 | test
Direct? False
Pipeline? True

PS> test 123
Direct? True
Pipeline? False

PS> test
Direct? False
Pipeline? False

Twitter This Tip! ReTweet this Tip!