loopspowershellcsvping

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


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:

$names = Get-content "hnames.txt"

foreach ($name in $names){
  if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
    Write-Host "$name is up" -ForegroundColor Green
  }
  else{
    Write-Host "$name is down" -ForegroundColor Red
  }
}

This gets me what I need but i now need to write out these results to a csv file and i have no idea how to do that.

Please Help!


Solution

  • 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