共用方式為


Iterating hash values to a log file

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.

Consider:

 $parameters = @{}
$parameters.Add("Parameter1","Value1")$parameters.Add("Parameter2","Value2")$parameters.Add("Parameter3","Value3")

$parameters = @{}; $parameters.Add("Parameter1","Value1"); $parameters.Add("Parameter2","Value2"); $parameters.Add("Parameter3","Value3")

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:

 $orderedhash.Add("Parameter1","Value1")
$orderedhash.Add("Parameter2","Value2")
$orderedhash.Add("Parameter3","Value3")
$orderedhash.Add("Parameter4","Value4")
$orderedhash

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

That's all for now!

[dad joke alert]

Maybe we'll rehash this later.