• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1631
  • Last Modified:

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

0
moorereason
Asked:
moorereason
1 Solution
 
BSonPoshCommented:
You basically need to convert $col.key to an array instead of hastable keycollection

like
$keys = $col.keys | %{$_}

Try the code below
function create-logentry($col)
{
	$objLogEntry = New-Object System.Object
         $keys = $col.keys | %{$_}
	foreach ($name in $keys[$keys.count..0])
	{
		$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

0
 
moorereasonAuthor Commented:
That's what I needed.  Thanks!
0

Featured Post

Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now