I have been working on script that pulls ip addresses from a text file, and then pings them in a forever loop, if any are dead then the status output turn red, and also sends an email for alerting.
my script..
$hostnamestxt = "C:\ping_machines.txt"
$servers = get-content "$hostnamestxt"
$date = get-date
while ($true) {
$i++
Write-Host "-- Round $i Machines--" # -foregroundcolor black -backgroundcolor green
foreach($server in $servers){
if (test-Connection -ComputerName $server -Count 2 -Quiet )
{
write-host "$server is ONLINE" -foregroundcolor black -backgroundcolor green
}
else
{
$to = $server
switch ($to)
{
"192.168.252.37" {$device="RAPID"; break}
"192.168.252.39" {$device="Sash line Welder83"; break}
"192.168.252.40" {$device="Sash line Welder84"; break}
default {$device="error";exit}
}
write-host "$device, $server is OFFLINE/UNREACHABLE" -foregroundcolor black -backgroundcolor red
send-mailmessage -to "myemail" -subject "$device, $server is OFFLINE/UNREACHABLE at $date" -Body "$device, $server is OFFLINE/UNREACHABLE at $date"
}
}
}
the above works ok, but the issue i have is that when adding new devices to monitor, i have to add the ip in the txt file then also amend script and into the case statment.
what i would like to do, but not sure how to do is.. read the ip addresses from and excel spreadsheet, say from column A, and then the names will be in column B.
If any device is down it then translates the name from column B, and puts that into a variable to process later.
Any help much appreciated, as i am pretty much stuck at the moment.
Instead of specifying a text file, use a CSV. Then you can use the Import-CSV commandlet and it will turn the list into a collection of objects, which will have properties like IP and Name, depending on what you put in the list. You could even add something for criticality. I used your script and made a couple of really quick changes. Something like this should work.
CSV:
Script: