Shell – Powershell – Arrays all on one line

powershell

I'm new to Powershell so don't know a huge amount.

I have a menu and I have 2 options ("Add IP" and "List IP's")

The "Add IP" code is:

$UIP = Read-Host "Enter IP to whitelist"
$whitelist += $UIP

The "List IP" code is:

Write-Host "==== $Title Whitelist IPs ===="
Write-Host
Write-Host $whitelist

The only problem is that when I list the array it lists everything on the same line like this:

192.168.0.1192.168.0.2

when I would like to to display like this:

192.168.0.1
192.168.0.2

Best Answer

You do not have to use a loop to perfom this, if you do not want to perform any operations on each IP.

Simply use

Write-Host ($whitelist -join "`n")

This will inject a new line between each element in the array. I have compared the differences below:

$array = @('foo','bar')
write-host ($array -join "`n") 

Output:
foo
bar

versus

$array = @('foo','bar')
write-host $array

Output:
foo bar

Hope it helps.

Related Question