I saw a little discussion thread on Twitter this morning which I felt needed a little more room to explain. Plus since we're in ScriptingGames season beginners might like a few pointers. I always talk about PowerShell, objects and the pipeline. But sometimes what looks like a pipelined expression in the PowerShell ISE doesn't behave the way you might expect.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
Here's an example.
$c=0 While ($c -le 5) { $c $c++ }
If you run this, you'll see numbers 1 to 5 written to the pipeline. But if you try something like this it will fail.
$c=0 While ($c -le 5) { $c $c++ } | out-file foo.txt
You'll get an error about an empty pipe. In fact, in the PowerShell ISE you'll get a red squiggle under the | indicating this is not going to work. That's because PowerShell isn't writing to pipeline at the end of the scriptblock, but rather within in. Another way to think about it is at the While operator is not a cmdlet so the only thing writing objects to the pipeline is whatever commands are within the While loop.
What you can do is something like this:
$c=0 $a = While ($c -le 5) { $c $c++ } $a | out-file foo.txt
Here, I'm capturing the pipeline output from the scriptblock and saving it to a variable. Then I have objects I can use. Or if you wanted to be clever, you could use a subexpression.
$c=0 $(While ($c -le 5) { $c $c++ }) | get-member
This same behavior also applies to Do and the ForEach enumerator. The latter trips people up all the time.
$i=1..5 foreach ($x in $i) { $x * 2 } | out-file results.txt
You think you'll get the output of ForEach saved to the file, but you'll run into the empty pipeline again. You could use a variable and then pipe the variable to the file or use a subexpression. Even better, use a pipelined expression.
1..5 | foreach {$_*2} | out-file results.txt
Here I'm using the cmdlet ForEach-Object, which unfortunately has an alias of ForEach which confuses PowerShell beginners. So don't assume that just because you see a set of { } that you get pipelined output. Remember, cmdlets write objects to the pipeline, not operators.
Could.you use write-output to male the pipeline.work in the first.example?
I’m not sure where you are thinking you could use Write-Output. You can’t pipe the While loop to it.