Link to home
Start Free TrialLog in
Avatar of moorereason
moorereasonFlag for United States of America

asked on

How do I reverse a hash keycollection?

I'm trying to create a helper function that takes a hash and converts it to a simple object that I can add to an array, that I eventually pipe through Export-CSV.  The problem is that when I build the object from the hash, the members of the object are reversed from the order I entered them in the hash.

I would like to reverse the hash keys collection (System.Collections.Hashtable+KeyCollection) in my foreach loop to fix this annoyance.  I've included the helper function below with a sample call.

NOTE: When I enter this code on the command-line, it works fine, but inside a script, the results are backwards!!
function create-logentry($col)
{
	$objLogEntry = New-Object System.Object
	foreach ($name in $col.keys)
	{
		$objLogEntry | Add-Member -type NoteProperty -name $name -value $col.Item($name)
	}
	return $objLogEntry
}
 
create-logentry( @{ 'SamAccountName' = 'jpublic'; 'FirstName' = 'John'; 'LastName' = 'Public' } )

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of BSonPosh
BSonPosh
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of moorereason

ASKER

That's what I needed.  Thanks!