Good morning, I'm hoping this is an easy one;
I'm trying to get a Table to show in the terminal using Get-NetIPAddress
against an array of Servers. I can get the table, but it either makes a new table for each item or only holds the last object and I'd like to make it one full table. below is the code I have
$Servers = @(Test1,Test2)
foreach($Server in $Servers){
$GetIP = get-netipaddress -CimSession $Server -AddressFamily ipv4 -PrefixOrigin Manual | Select PSComputerName,IPAddress
$GetIP | Format-Table
}
CodePudding user response:
Use ForEach-Object
to construct a single pipeline that outputs to Format-Table
:
$Servers |ForEach-Object {
Get-NetIPAddress -CimSession $_ -AddressFamily ipv4 -PrefixOrigin Manual
} |Format-Table PSComputerName,IPAddress
As long as Format-Table
is expecting more input from the upstream cmdlet, it'll just continue populating the same table.
Alternatively, use the -HideTableHeaders
parameter to suppress repeated headers - only problem is you need the first invocation to actually include the table headers, but you could do something like:
# We'll use this hashtable to control the table header visibility
$FTParams = @{ HideTableHeaders = $false }
foreach($Server in $Servers){
$GetIP = get-netipaddress -CimSession $Server -AddressFamily ipv4 -PrefixOrigin Manual | Select PSComputerName,IPAddress
$GetIP | Format-Table @FTParams
# Format-Table has run at least once, we can start hiding the headers
$FTParams['HideTableHeaders'] = $true
}
CodePudding user response:
You are outputting the table within the foreach scriptblock, so Format-Table
will naturally be creating a new table on each call.
The best option is to use piping as in Mathias answer. Send all objects in one stream to Format-Table.
But if you like to spell the process out for better understanding, build an array and then use it when finished.
$Servers = @(Test1,Test2)
[array]$result = $null
foreach($Server in $Servers){
$result = Get-NetIpAddress -CimSession $Server -AddressFamily ipv4 -PrefixOrigin Manual | Select PSComputerName,IPAddress
}
$result | Format-Table