Creating objects from ordered hash tables in Powershell V3

One of the new things the added in Powershell V2 was the ability to create new PSObjects from a hash table.

If you use this featuture you’ll be happy to hear that it gets even better in V3.

The biggest irritation of using hash tables to create objects is that hash tables don’t enumerate in any predictable order.

If you create objects from a hash table, and then display them the properties do not come out in the same order as they appear in the hash table, and have to be re-ordered with select-object to get them back into the desired order.

I posted a workaround here:

https://mjolinor.wordpress.com/2011/10/08/new-object-from-a-hash-table-in-a-script-block/

It works, but it’s ugly.

There is a specialized form of hash table called an ordered hash that will enumerate in order, but New-Objedt doesn’t use it properly.

Thanks to Roman Kuzmin submitting a request to get this fixed, everybody who voted for it, and Microsoft for doing it, we now have a better option.

http://connect.microsoft.com/PowerShell/feedback/details/680572/the-property-parameter-of-new-object-should-be-IDictionary-not-hashtable

In V3 there is now a type accelerator for ordered hash tables ([ordered]) and New-Object will work properly with those hash tables.

Using the same code from the other example, it now looks like this using the the ordered hash.

$input = netstat -n  
$regex = "\s\s(\S+)\s+(\S+):(\S+)\s+(\S+):(\S+)\s+(\S+)"  

$props = {  
	[ordered]@{
		State = $matches[6]  
		Protocol = $matches[1]  
		LocalAddress = $matches[2] -as [ipaddress]  
		LocalPort = $matches[3]  
		ForeignAddress = $matches[4] -as [ipaddress]  
		ForeignPort = $matches[5]  
		}  
	}  

$input_data | foreach-object {  
	if ($_ -match $regex){  
	new-object psobject -property (&$props) 
	}  
} 

The ugly code that was needed to parse out the property list is gone, along with the select-string that was needed to re-order the properties so they come out in the same order as the hash table entries.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s