Search code examples
powershellfor-looppowershell-4.0powershell-5.0

Conver the result of a for loop to a table


I can't convert the following for loop to a table:

for ($i=1; $i -le 10; $i++) 
{ 
    $ErrorActionPreference= 'silentlycontinue' 
    Write-Progress -PercentComplete ((100*$i)/255) -Activity "Gathering IP's"  

    nslookup("192.168.2." + $i) | Format-Table
}

The only thing that happens is that for every adress that is not reachable, it shows the router name/ip:

Server:  easy.box.local
Address:  192.168.2.1

Name:    easy.box.local
Address:  192.168.2.1

Server:  easy.box.local
Address:  192.168.2.1

I want to sort it like a table to make it more convinient and more viewable


Solution

  • If you are on a Windows 8 or later machine you could use [System.Net.Dns]::Resolve (Note that unsuccessful lookups will have the IP address as the hostname)

    for ($i=1; $i -le 10; $i++) { 
        Write-Progress -PercentComplete ((100*$i)/255) -Activity "Gathering IP's"  
        [System.Net.Dns]::Resolve("192.168.2." + $i) | Select HostName,AddressList
    }