HOWTO: Create Fastest Possible Custom Objects [Revisit]

In November of last year I did a post called the "Fastest Possible Way to Make Custom Objects in PowerShell".

That post came about because I was frustrated with the techniques I was using at the time to make custom objects and decided to sit down and once and for all simply the process.
If you have a look at that code, you’ll see using it was simple enough but initializing it was all sorts of bizarre.

I’m pleased to say that in the year since I’ve wrote that post, I’ve learned a lot about PowerShell. I’ve learned that I made things far, far more complicated than it needed to be.*
(* The technique above technically is still useful for PowerShell 2 environments as the technique below I’m pretty sure isn’t supported there)

Let’s say you want to make a custom object.  Specifically let’s say you want to show the filename of all files in a folder and the first line of each file.  Look how easy this is now:

Get-ChildItem c:\windows\*.log | % { [pscustomobject]@{‘Filename’=$_.fullname; ‘FileContent’= (Get-Content $_.fullname | select -first 1)} }

If that doesn’t make any sense, here is the important part.  To make a custom object, do the following:


You’re using a "type accelerator" called [pscustomobject] and defining it as a hash table (series of key/value pairs).  The right side of the equals in each line can be wrapped in round brackets allowing you to run anything you want and save it into the final object, just as I did above with Get-Content.

Very cool stuff!

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.