user5955036
user5955036

Reputation:

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

Upvotes: 1

Views: 101

Answers (2)

BenH
BenH

Reputation: 10034

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
}

Upvotes: 0

Martin Brandl
Martin Brandl

Reputation: 58931

You could use regex to grab the information and create a new object which will make it sortable:

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

    $nsLookupResult = nslookup("192.168.2." + $i)
    [PSCustomObject]@{
        Server = [regex]::Match($nsLookupResult,'Server:\s+(\S+)').Groups[1].Value
        Address = [regex]::Match($nsLookupResult,'Address:\s+(\S+)').Groups[1].Value
    }
}

Output:

Server           Address        
------           -------        
easy.box.loca 192.168.150.254
easy.box.loca 192.168.150.254
easy.box.loca 192.168.150.254
easy.box.loca 192.168.150.254
easy.box.loca 192.168.150.254
easy.box.loca 192.168.150.254
easy.box.loca 192.168.150.254
easy.box.loca 192.168.150.254
easy.box.loca 192.168.150.254
easy.box.loca 192.168.150.254

Note: There might be a builtin PowerShell cmdlet which would make this obsolete.

Note 2: You only have to set the $ErrorActionPreference once thats why I set it outside the for loop.

Upvotes: 1

Related Questions