Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 355
Harry Singh Avatar asked Dec 03 '22 17:12

Harry Singh


1 Answers

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

like image 114
Erez breiman Avatar answered Dec 06 '22 11:12

Erez breiman