Ping a list of host names and output the results to a csv in powershell
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
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"
I would do it this way. Using a list of computers and -asjob works very well. The Responsetime property (confusingly the header is "Time(ms)") will be non-null if the host is up.
$names = Get-content hnames.txttest-connection $names -asjob -count 1 | receive-job -wait -auto
Source Destination IPV4Address IPV6Address Bytes Time(ms)------ ----------- ----------- ----------- ----- --------COMP001 yahoo.com 74.6.231.21 32 39COMP001 microsoft.com 40.113.200.201 32