我正在尝试获取IP列表,并使用Powershell将其解析为DNS名称。如果主机无法解析,我会尝试将其写出到错误文件中。目前,该脚本在能够解析到主机名的IP上运行得非常快(小于10ms),但对于不能解析的IP,脚本需要较长的时间(每个IP大约4500毫秒)。我已经尝试在非解析is上对DNS解析进行计时,当它们失败时,我得到大约65毫秒,所以我不确定是什么给解析增加了超过4000毫秒的额外拖动时间。当处理超过1,000个IP时,这将是一个非常密集的计时过程。下面的脚本包含我用于故障排除的测量命令语句。
$ips = get-content ".\source_ip.txt"
$outFile = ".\resolvedTest.txt"
$errorFile = ".\resolveErrorTest.txt"
$commandTimes = @()
foreach ($ip in $ips){
$measure = Measure-Command{
try {[string] $hostname = [System.Net.Dns]::GetHostByAddress($ip).HostName}
catch [system.exception]{$hostname = $ip}
$hostname = $hostname.Replace("@{HostName=","")
$hostname = $hostname.Replace("}","")
if ($hostname -eq $ip){
Add-Content $errorFile "$hostname, Error"
} else {
Add-Content $outFile "$ip, $hostname"
}
}
Write-Host $measure.TotalMilliseconds
$commandTimes += ,$measure.TotalMilliseconds
}发布于 2015-11-15 17:36:55
我尝试删除不必要的语句:
$ips = "127.0.0.1", "127.0.0.1"
$outFile = "c:\resolvedTest.txt"
$errorFile = "c:\resolveErrorTest.txt"
foreach ($ip in $ips){
$measure = Measure-Command {
try {
$hostname = [System.Net.Dns]::GetHostByAddress($ip).HostName
}
catch {
$hostname = $false
}
}
if($hostname) {
Write-Host ("$ip was successfully resolved to $hostname ({0:N0}ms elapsed)" -f $measure.TotalMilliseconds) -ForegroundColor Green
} else {
Write-Host ("$ip was not resolved ({0:N0}ms elapsed)" -f $measure.TotalMilliseconds) -ForegroundColor Red
}
}不过,我不知道这样做会不会更快。
https://stackoverflow.com/questions/33501097
复制相似问题