Generating Output as Objects

PowerShell is based on objects. Objects are sent down a pipeline. Cmdlets take objects as input and emit objects as output. Scripts and Functions should do this as well. This enables end users to take advantage of thins like Format-Table, Format-List, Export-Csv, and ConvertTo-HTML

This is pretty easy if you are getting an single object and returning a single object. But what if you wanted to create a new object that was a combination of several source objects. This would be like a Join in SQL. You can create what is called a PSObject using the New-Object Cmdlet.

I have seen a lot of people in the Scripting Games use this technique very effectively. Let’s look at a quick example

image

This is great but there is a trick that might make life a bit simpler. You can pass in a hash table to New-Object which eliminates a few lines and make things a bit easier to read and understand.

image

Comments are closed