我如何加快此Powershell循环

时间:2019-07-12 15:02:38

标签: powershell

我在Powershell方面非常陌生,但最近我决定尝试重新创建一个有时会用作Powershell脚本的旧工具。该脚本接受用户输入以获取IP范围,然后ping,获取主机名,检查服务是否存在并正在运行,然后将其导出到CSV文件。我还没有对代码进行太多清理。它可以满足我的要求,但是当我在更大的IP范围上进行测试时,即花费了几分钟。 1-254用了大约10分钟。任何提示将不胜感激。

Add-Content -Path ".\$fullrange.csv"  -Value '"Ping","IP","Hostname","Service State","Startup","Version"'

  ForEach($IP in $range) {
    $status = test-connection -computername ($IP) -count 1 -Quiet -ErrorAction SilentlyContinue
    if ($status) {
      $hostname = [System.Net.Dns]::GetHostbyAddress("$IP")."HostName"
      $service = Get-WmiObject -Class Win32_Service -ComputerName $IP -ErrorAction SilentlyContinue | Where-Object Name -like "SysaidAgent"
      if ($service) {
        $xml = [xml](Get-Content "\\$IP\C$\Program Files\SysAid\Configuration\AgentConfigurationFile.xml")
        $ver = $xml.SelectSingleNode("//AgentVersion")."#text"
      }
      else{
        $service = "Not Found"
        $ver  = "N/A"
      }
      Add-Content -Path .\$fullrange.csv  -Value "$status,$IP,$hostname,$service.state,$service.startmode,$ver"
    }
    else{
      Add-Content -Path .\$fullrange.csv  -Value "$status,$IP"
    }
  }

0 个答案:

没有答案