Is it possible to have conditional pipes in PowerShell?

Say I only want to pass my output to another function depending on the value of the variable, is there a way to do this in powershell?

Example:

if ($variable -eq "value"){$output | AnotherFunction} else {$output} 

An @mjolinor example is how I do it now, just curious if there is a better way to do this.

+4
source share
4 answers

You can use the If clause:

  if ($variable -eq "value"){$output | AnotherFunction} else {$output} 

The example is implemented as a symbol:

  filter myfilter{ if ($variable -eq "value"){$_ | AnotherFunction} else {$_} } 

Then:

  $variable = <some value> get-something | myfilter 
+6
source

You can get the results you are looking for by connecting to the Where-Object .

Example:

My-Command | Where-Object {$variable -eq "value"} | AnotherFunction

+2
source

If another function belongs to you, you can send $ variable as a parameter, and let your function pass the object through unmodified when the parameter is true. Essentially, you are using AnotherFunction () as a Mjolinor filter.

0
source

In this question, I asked how to use if inside the pipeline. It demonstrates how to transfer data to other functions based on conditions.

0
source

All Articles