• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1729
  • 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

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