2015-11-03 81 views
1

我正在嘗試使用Powershell將IP列表解析爲DNS名稱。如果主機無法解決問題,我試圖將其寫入錯誤文件。目前,腳本在能夠解析爲主機名的IP上運行速度非常快(小於10毫秒),但對於不能解析腳本的腳本需要較長的時間(每IP大約爲4500毫秒)。我已經試過只對未解析的IP進行DNS解析,並且當它們失敗時我大概可以獲得65毫秒的時間,所以我不確定什麼會將4000多ms的額外拖動時間添加到解析度。處理超過1,000個IP時,這將成爲一個非常密集的計時過程。下面的腳本包含我一直用於故障排除的測量命令語句。DNS解析速度令人難以置信

$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 
    } 
+0

'[System.Net.DNS] :: GetHostByAddress($ ip).HostName'應該是一個字符串。無需Casting [string] $ hostname。這兩行使用'.Replace()'是不必要的。刪除這些將有助於提高速度,但可能這不是問題。 這是反向DNS,所以沒有我知道的原生cmdlet會這樣做,並希望包含超時。 另外,您可以刪除if結構,並將錯誤部分移至catch塊,以取代設置$ hostname並移動輸出部分的部分。你最終會用'try {}; catch {};添加內容....' – Xalorous

回答

0

我試圖消除不必要的語句:

$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 
    } 

} 

不知道這是否會更快,雖然。

相關問題