Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format the output of a hash table in Powershell to output to one line

Is it possible to format the output of a hashtable in Powershell to output all the values onto one line?

e.g.

I have the hash table $hashErr with the below values:

 $hashErr = @{"server1" = "192.168.17.21";
              "server2" = "192.168.17.22";
              "server3" = "192.168.17.23"}

Which are written to a log with the below:

$hashErr.GetEnumerator() | Sort-Object Name | ForEach-Object {ForEach-Object {"{0}`t{1}" -f $_.Name,($_.Value -join ", ")} | Add-Content $log

The will cause the below to be written to the log:

    Name                           Value
    ----                           -----
server2                        192.168.17.22
server1                        192.168.17.21
server3                        192.168.17.23

My question is, how can I format this hash table so the output is written all to one line, like the below?

server2 192.168.17.22 | server1 192.168.17.21 | server3 192.168.17.23

This could be done by looping through all the values in the hash table and putting them into an array but surely there is a more direct way?

like image 655
user_invalid Avatar asked Jan 07 '14 15:01

user_invalid


People also ask

How do I display output in a table format in PowerShell?

Using Format-Table for Tabular Output. If you use the Format-Table cmdlet with no property names specified to format the output of the Get-Process command, you get exactly the same output as you do without a Format cmdlet. By default, PowerShell displays Process objects in a tabular format.

How do I read a Hashtable in PowerShell?

By default, a hash tables is displayed as a table with one column for keys and one for values. Hash tables have Keys and Values properties. Use dot notation to display all of the keys or all of the values. Each key name is also a property of the hash table, and its value is the value of the key-name property.

How do I merge two hash tables in PowerShell?

Adding values of the hash table is simple as the adding string. We just need to use the addition operator (+) to merge two hash table values.


1 Answers

Not excat output as you want but also 1 line output.

$hashErr | ConvertTo-Json -Compress

outputs:

{"server2":"192.168.17.22","server3":"192.168.17.23","server1":"192.168.17.21"}
like image 183
Gerrit Geeraerts Avatar answered Oct 13 '22 03:10

Gerrit Geeraerts