Can someone please explain Why my first examples don't work, and why adding in a ForEach-Object solves the problem? Thanks in advance!
I parsed the return from a command into a hashtable (sample at end of post) and want to log the information to a file as part of my processing. I know that $ht.GetEnumerator() | Sort-Object Name
will return the full hash to screen, sorted. However, once I try sending things to file, it breaks.
$ht | Add-Content log.txt
only logs a single row of System.Collections.Hashtable
. So, I've also tried
$ht.GetEnumerator() | Sort-Object Name | Add-Content log.txt
and end up with rows of
System.Collections.DictionaryEntry
System.Collections.DictionaryEntry
System.Collections.DictionaryEntry
So then I tried to loop through and handle each individually with
foreach ($key in $ht.keys) {
Add-Content log.txt "$key : $ht.$key" }
and end up with
Server address : System.Collections.Hashtable.Server address
Client address : System.Collections.Hashtable.Client address
User name : System.Collections.Hashtable.User name
Solved with:
$ht.GetEnumerator() | Sort-Object Name |
ForEach-Object {"{0} : {1}" -f $_.Name,$_.Value} |
Add-Content log.txt
For reference, the hashtable sample:
$ht = @{
"Server address" = "server.net";
"Client address" = "10.20.121.153";
"User name" = "myuser"
}
In the first method, the one that I prefer, you can use the GetEnumerator method of the hash table object. In the second method, instead of iterating over the hash table itself, we loop over the Keys of the hash table. Both of these methods produce the same output as our original version.
Printing hashtable: To print /display a hashtable, just type the variable name in which hashtable is saved. The above command displays a table with two columns, one for keys and the other one for the associated values for the keys.
GetEnumerator. A hash table is a single PowerShell object, to sort, filter or work with the pipeline you can unwrap this object into it's individual elements with the GetEnumerator() method.
I agree with mjolinor... just not enough points to vote up... plus i'll add that you dont need the GetEnumerator
$ht | out-string | add-content log.txt
will do it.
As you can see in Microsoft documentation a hash table is simply a collection of name-value pairs.
So $ht
is really System.Collections.Hashtable
composed of System.Collections.DictionaryEntry
.
A good way to use it is
foreach ($i in $ht.keys)
{
add-content log.txt ("{0} {1}" -f $i, $ht[$i])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With