6

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

Example :

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

@mjolinor's example is how I am doing it now, just curious if there is a better way to do it.

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486

4 Answers4

6

You can use an If clause:

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

Example implemented as a fiter:

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

Then:

 $variable = <some value>
 get-something | myfilter
mjolinor
  • 66,130
  • 7
  • 114
  • 135
3

You may get the results you are looking for by piping to the Where-Object.

Example:

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

daalbert
  • 1,465
  • 9
  • 7
  • I don't see how that would allow conditional piping. Do you have an example? – Abe Miessler May 19 '11 at 16:50
  • Do you want to output to different functions depending on the output, or do you want to output to 1 function, but only if the output is what you want it to be? – daalbert May 19 '11 at 17:07
  • Pretty much the way that @mjolinor has it setup. I was wondering if there was a better way, but it sounds like there might not be. – Abe Miessler May 19 '11 at 17:24
  • I updated my answer with an example. AnotherFunction will get passed only what passes the condition of Where-Object. – daalbert May 19 '11 at 17:34
  • 1
    But when $variable -eq "value" is $false, nothing is returned. That's why this approach doesn't work. – stej May 19 '11 at 18:17
  • @stej that is correct, but many functions/cmdlets will gracefully exit when passed nothing. Try running `Get-Process | Where-Object {$_.handles -lt 100} | Format-List`, then change the 100 to 0 and run it again. – daalbert May 19 '11 at 18:40
0

If the other function is yours, you can send $variable as a parameter and let your function pass the object through unmodified when param is true. Essentially, you use AnotherFunction() as Mjolinor's filter.

codepoke
  • 1,272
  • 1
  • 22
  • 40
0

In this question I've asked how to use if statements inside pipeline. It demonstrates how to pipe data to other functions based on conditions.

Community
  • 1
  • 1
Emiliano Poggi
  • 24,390
  • 8
  • 55
  • 67