Convert PowerShell Object to Hashtable Revised

squarepatternA while back I posted an advanced PowerShell function that would take an object and convert it to a hashtable. The premise was simple enough: look at the incoming object with Get-Member to discover the property names then create a hashtable with each property name as a hashtable key. I’ve a need to use this over the last few weeks and realized the function could use a little updating.

The new version works like the old, with the addition of one new parameter. I decided I wanted a way to exclude properties from the hashtable. Of course this presumes you know in advance about the object you are working with and what properties you wish to exclude. This is the core segment of code, which has also been revised over version 1.

In the first version I was duplicating some code and I generally try to avoid that. In this snippet $names is the collection of property names and $Inputobject is the piped in object. Armed with this tool I can create hashtables from objects with just the properties I want.

This version should work in PowerShell 2.0 or 3.0. Download ConvertTo-Hashtable2.

6 thoughts on “Convert PowerShell Object to Hashtable Revised

  1. This is a great function that I use very often. But I have change it additionally with a $Inclue parameter.

    How it works:
    If the [String[]] $Include Count ist equals to 0, then use the Get-Member function to get the member name, it its greather than 0, us this assignment: $names = $Include.


    • I might want to take the object and transform it. Using a hashtable and modifying it is pretty easy. The hashtable can then be turned back into an object. Or I might want to combine objects. Much easier to join a few hash tables and then turn that back into an object. Or I might want a hash table of properties that I can splat later against some other cmdlet.

  2. Pingback: Join PowerShell Hash Tables | The Lonely Administrator

Comments are closed.