Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 将for循环的结果转换为表_Powershell_For Loop_Powershell 4.0_Powershell 5.0 - Fatal编程技术网

Powershell 将for循环的结果转换为表

Powershell 将for循环的结果转换为表,powershell,for-loop,powershell-4.0,powershell-5.0,Powershell,For Loop,Powershell 4.0,Powershell 5.0,我无法将以下for循环转换为表: 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 } 唯一发生的事情是,对于每个无法访问的地址,它

我无法将以下for循环转换为表:

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
}
唯一发生的事情是,对于每个无法访问的地址,它都会显示路由器名称/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
我想将它像表格一样进行排序,使其更方便、更可查看

您可以使用正则表达式获取信息并创建一个新对象,使其可排序:

$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
    }
}
输出:

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
注意:可能存在一个内置的PowerShell cmdlet,这将使此应用程序过时


注意2:您只需设置一次
$ErrorActionPreference
,这就是我在for循环之外设置它的原因。

如果您在Windows 8或更高版本的计算机上,您可以使用[System.Net.Dns]::解析(注意,不成功的查找将以IP地址作为主机名)


感谢您的回复,但是如果您测试您的脚本,您会注意到,如果查找成功与否,它将始终输出相同的ip地址。这是NSLookup的输出。对于不同的方法,请尝试“Get-NetIPAddress-IPAddress 192.168.2.*Format Table”,这实际上相当简洁!谢谢你的回复
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
}