Iterating hash values to a log file

Iterating hash values to a log file

Be the first to vote!

While working on my last script, I was trying to figure out the best way to write the values stored in a hash table for the purposes of splatting out to a log file.


$parameters = @{}

I was using a modified version of my logging function, which is basically a wrapper for Add-Content with parameters for log detail/types, colors, and output display.

One of the “display” things I wanted to fix was to make sure that each parameter showed up on its own line in console output or in the log file.  To that end, this didn’t work:

So, instead of printing the objects in the table, it just prints, “Hi, I’m a hashtable.”  Not the most useful thing if you’re trying to capture detailed data. I also tried a few other things:

What I ended up doing to get the display the way I wanted:

$parameters.GetEnumerator() | % { Write-Log -LogLevel DEBUG -ConsoleOutput -Message "Parameter Name:$($_.Name); Paramater Value: $($_.Value)" }
[2019-01-15 10:37:09] [DEBUG] :: Parameter Name:Parameter2; Parameter Value: Value2
[2019-01-15 10:37:09] [DEBUG] :: Parameter Name:Parameter1; Parameter Value: Value1
[2019-01-15 10:37:09] [DEBUG] :: Parameter Name:Parameter3; Parameter Value: Value3

Using the GetEnumerator() method on the hash returned the parameter key/value pair, and allowed me to reference them independently using $_.Name (Key) and $_.Value (Value).

Armed with the appropriate data, I could capture each parameter / value pair in the hash table and send them to either the display or log file.

Semi-pro tip: You’ll notice that I had added my parameters to the hash table using the Add() method in a one order, but the system returned them to me in a different order.  It didn’t matter from the splatting perspective, but if you want to set a defined order that values are stored, you can use the [ordered] property when creating the hash:


Name Value
---- -----
Parameter1 Value1
Parameter2 Value2
Parameter3 Value3
Parameter4 Value4

That’s all for now!

[dad joke alert]

Maybe we’ll rehash this later.

Published by Aaron Guilmette

Helping companies conquer inferior technology since 1997. I spend my time developing and implementing technology solutions so people can spend less time with technology. Specialties: Active Directory and Exchange consulting and deployment, Virtualization, Disaster Recovery, Office 365, datacenter migration/consolidation, cheese.

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Exit mobile version