Ping a list of host names and output the results to a csv in powershell

后端 未结 4 1879
一生所求
一生所求 2020-12-16 07:52

I have a large list of hostnames I need to ping to see if they are up or down. I\'m not really that great at scripting but I managed to figure this much out:



        
相关标签:
4条回答
  • 2020-12-16 08:38

    I would do it this way. Using a list of computers and -asjob works very well. The Responsetime property will be non-null if the host is up.

    $names = Get-content hnames.txt
    test-connection $names -asjob -count 1 | recieve-job -wait -auto
    
    0 讨论(0)
  • 2020-12-16 08:44
        $Output= @()
        $names = Get-Content ".\input\Servers.txt"
        foreach ($name in $names){
          if (Test-Connection -Delay 15 -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
           $Output+= "$name,up"
           Write-Host "$Name,up" -ForegroundColor Green
          }
          else{
            $Output+= "$name,down"
            Write-Host "$Name,down" -ForegroundColor Red
          }
        }
        $Output | Out-file ".\output\result.csv"
    

    This is a tad cleaner, and includes the original foreground options but, BTW, the 'delay' switch seems to be ignored -PB

    0 讨论(0)
  • 2020-12-16 08:57

    I am a complete newbie to Powershell, so I took this on as a learning task, as I needed a quick and simple way to check a list of PC's for up/down status. These tweaks were needed to get it to output cleanly to the screen and to a txt file

    $Output= @()
    $names = Get-content "hnames.txt"
    foreach ($name in $names){
      if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
       $Output+= "$name,up"
       Write-Host "$Name,up"
      }
      else{
        $Output+= "$name,down"
        Write-Host "$Name,down"
      }
    }
    $Output | Out-file "C:\support\result.csv"
    
    0 讨论(0)
  • 2020-12-16 08:59

    You can use the following code instead (I simply altered the write-host calls to CSV formatting) and execute it with "PowerShell.exe script.ps > output.csv" Note that you must execute it from the folder that contains hnames.txt, or simply change the "hnames.txt" to a full path.

    $names = Get-content "hnames.txt"
    
    foreach ($name in $names){
      if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
        Write-Host "$name,up"
      }
      else{
        Write-Host "$name,down"
      }
    }
    

    P.S. You can also use the Out-File Cmdlet to create the CSV file

    0 讨论(0)
提交回复
热议问题