Powershell hashtable does not write to file as expected - receive only "System.Collections" rows Powershell hashtable does not write to file as expected - receive only "System.Collections" rows powershell powershell

Powershell hashtable does not write to file as expected - receive only "System.Collections" rows


Answering the why part, you obviously have a solution :)

In your first example

$ht | Add-Content log.txt

PowerShell takes $ht and tries to somehow convert it to a string so that it can be stored via Add-Content. Because there is no conversion defined for the hashtable, only the type name is returned from the conversion. Same as for example new-Object Random|Add-Content d:\log.txt. Again, only type name is written.

Next

$ht.GetEnumerator() | Sort-Object Name | Add-Content log.txt 

is similar. GetEnumerator returns object that is used for iteration; objects of type System.Collections.DictionaryEntry are returned. Again, there is no conversion to string, so type names are returned.

Personally, I think PowerShell should be smart enough and help here. The question is "how?". Designers probably didn't want to hardcode the output. It might be "{key}: {value}" or "{key} = {value}", or "{key}/{value}", or ... The format is not clear, so they left it for us to decide and format as you did it with the foreach statement.


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.


Your first example does not work, or better, partially works, because you are trying to get a property value within the string. Normally, inside strings, the parser is able to resolve only direct variables (like $key). To resolve more complex variable you need parenthesis.

For the loop, this should work:

foreach ($key in $ht.keys) {Add-Content log.txt "$key : $($ht.$key)" }

or even better

$ht.keys | %{ Add-Content log.txt "$_ : $($ht.$_)" }