Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell output contents of hash to file

I have code to output a sorted hashtable to the screen:

$h.getenumerator() | sort value -descending

It looks like this:

Name                           Value
----                           -----
10.10.10.10 69566308           151
10.10.10.11 69566308           143
10.10.10.12 69566308           112
10.10.10.13 69566308            99
10.10.10.14 69566308            71
10.10.10.15 69566308            70

But I would like to output this to a file instead.

When I try to output to a file with

$h.getenumerator() | sort value -descending | out-string | Add-Content D:\Script\iis_stats.log

or

$h.getenumerator() | sort value -descending | Add-Content D:\Script\iis_stats.log

All I get is "System.Collections.DictionaryEntry" in D:\Script\iis_stats.log.

How do I fix it?

like image 417
Glowie Avatar asked Jan 25 '26 00:01

Glowie


2 Answers

If you want it in the same format it displays on the screen (folded at the pipes for readability):

$h.getenumerator() | 
  Sort-Object value -descending | 
  Format-Table | 
  Out-String | 
  Add-Content D:\Script\iis_stats.log
like image 61
mjolinor Avatar answered Jan 26 '26 17:01

mjolinor


You would get similar output on your screen if you did something like this as well:

$h.GetEnumerator() | sort value -Descending | ForEach-Object{
    $_.GetType().FullName
}

For every entry you would see System.Collections.DictionaryEntry since it does not have a proper string equivalent.

Then you should just do what mjolinor suggests. PowerShell automatically appends the | Out-Default command to the console so that it displays in a way that is visually pleasing. When you send the output to Add-Content that prettification cannot occur.

like image 44
Matt Avatar answered Jan 26 '26 16:01

Matt