Powershell, Where-Object and capturing the output

Again, one that thing I couldn’t find because there is just no documentation on Powershell.

Try this:

$foo = SomethingThatResturnsAList

$foo = $foo | ? { $_.Name -like "*something*" }

PassOnFooToSomethingElse -List $foo

Awesome, every sane developer would think: right, that would work. Except in Powershell.

It appears that $foo on line 5 is $null

WHAT?

Okay, let’s surround it with braces, maybe that’ll solve stuff:

$foo = ( $foo | ? { $_.Name -like "*something*" } )

But that doesn’t work either.

Now for the solution, I’d love to point you out to a link on the world wide web where you can view the documentation, but honestly, I just can’t find it…

The solution is to replace the 3th line by this: $( … ), like this:

$foo = $( $foo | ? { $_.Name -like "*something*" } )

And that works.

Happy coding & have a good one,

-Kristof

This entry was posted in Powershell, Programming and tagged , , . Bookmark the permalink.