I am trying to write something simple, using Powershell Test-Connection, to be able to ping a list of IPs from a reference file and output an up or down status. All IPs are for ASA ports not actual servers, so they don't have true hostnames. I can't get the script to work with "nicknames" attached to the IPs in the reference file. Without some sort of name attached to the IP in the output, this tool is no better than looking up individual IPs to ping.
What I have so far:
$complist = Get-Content "Path"
foreach($comp in $complist){
$pingtest = Test-Connection -ComputerName $comp -ErrorAction SilentlyContinue
if($pingtest){
Write-Host($comp + " is online")
}
else{
Write-Host($comp + " is not reachable")
}
}
My reference txt file:
1.1.1.1 nickname
2.2.2.2 nickname2
Even if the port is reachable, the output claims not reachable because DNS cannot reconcile "hostname" with IP.
Use the String.Split()
method to split the string on whitespace:
$complist = Get-Content "Path"
foreach ($line in $complist) {
# extract ip and nick into separate variables
$ip,$nickname = $line.Split()
# ping
$pingtest = Test-Connection -ComputerName $ip -Quiet
# output (with nickname) message with status
if ($pingtest) {
Write-Host "${nickname} [${ip}] is online"
}
else {
Write-Host "${nickname} [${ip}] is offline"
}
}