Emitting Objects verses Outputting Text to the Screen
Let’s face it, PowerShell does a bunch of magic for you. If we’ve done our job right, this magic is exactly what you want 99 out of a 100 times. That said, if you are a power user, then at some point you’ll encounter that 100th case and you’ll need to understand the magic so you can get PowerShell to do exactly what you want. The good news is that our “magic” is pretty thoughtful and you can always get exactly what you want (usually with very little effort).
The biggest source of magic is the formatting and outputting. You write a function which just emits an object and wham – you get a reasonable view of that object. If you want something different, you can easily control that with the formatting commands. Things gets a little trickier if and when you need to understand the difference between formatting and outputting.
Our formatting commands emit FORMAT OBJECTS which then USUALLY get auto-routed to an OUT-XXX command. You can write functions where this does not happen and you can get surprised if you aren’t aware of what is going on. James O’Neill has a great blog entry on this very issue here: PowerShell Again. Pipes, and “This is not an output” . James wrote a very clever function which displays processes and allows you to choose one. It came upon this issue. All it takes is a well placed ” | Out-Host” to fix the problem (I told you you’d be able to get exactly what you want with very little effort).
Jeffrey Snover [MSFT]
Windows Management Partner Architect
Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx
Random Note: I’ve been trying to keep up with the wonderful advances being made in the world of material science and nanotubes in particular. I was reading Dr Zelia Zanolli’s blog about her work on a project attempting to functionalize nanotubes. She posted a nanotube play on the painting “The Treachery of Images” which is a painting of a Pipe with the words “Ceci n’est pas une pipe” (this is not a pipe) HERE . James’s blog has a cartoon spoof of the same painting. Talk about Synchronicity.