0

I want to display a hashtable in PowerShell and I want to use an array to fill one of the columns.

Basically, what I have is this:

$Servers = "training01.us", "training02.us", "training03.us"

#Table
$table = @(@{ColumnA="$Servers";ColumnB=online})
$table.ForEach({[PSCustomObject]$_}) | Format-Table -AutoSize

What I would want it to do is display each server on a different row in the table. For example:

ColumnA
-------
training01.us
training02.us
training03.us

But instead I get this displayed:

ColumnA
-------
training01.us training02.us training03.us

How can I fix this?

1
  • from what i can tell you will either need to write your own format code OR make a hashtable with one value per key instead of an array in the value. Commented Jan 28, 2019 at 23:56

1 Answer 1

2

This should give you the desired output:

$Servers = "training01.us", "training02.us", "training03.us"
$OFS = "`n"
$table = @(@{ColumnA="$Servers";ColumnB='online'})
$table.ForEach({[PSCustomObject]$_}) | Format-Table -AutoSize -Wrap

Beware, though, that all servers are still in the same field (as a single string). The three name strings are merely joined with newlines (by setting the Output Field Separator to `n).

Format-Table -Wrap then displays the wrapped string value without truncating the output.

Another way to the same result (without having to modify $OFS) would be

$table = @(@{ColumnA=$Servers -join "`n";ColumnB='online'})
$table.ForEach({[PSCustomObject]$_}) | Format-Table -AutoSize -Wrap
Sign up to request clarification or add additional context in comments.

4 Comments

Both of them worked fine. Just out of curiosity, would it be possible to make them separate strings? I don't need the code for that, just curious.
Possible: yes. However, PowerShell doesn't normally organize data in columns. Attempts to do so tend to be awkward.
would this change if ColumnB had a variable inside it that is an array like $Servers?
Maybe, mabe not. It depends on what data you have.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.