- Joined
- Dec 1, 2010
- Location
- Doylestown, Ohio
Hey all,
I'm kind of new to scripting and what have you, but I needed something to suit a particular task: I need to ping a list of PCs at all times, and if it becomes alive, I need to know about it. (Passively, I don't need an alert or anything)
I figured the best way to do this was in powershell. I pieced this together with a ton of googling. I'm open to suggestions/improvements as well if you guys have them.
One thing that I cannot figure out, is why when I add to an array, it outputs the array index to the console. If anyone has tips of suppressing that, please let me know.
I'm kind of new to scripting and what have you, but I needed something to suit a particular task: I need to ping a list of PCs at all times, and if it becomes alive, I need to know about it. (Passively, I don't need an alert or anything)
I figured the best way to do this was in powershell. I pieced this together with a ton of googling. I'm open to suggestions/improvements as well if you guys have them.
One thing that I cannot figure out, is why when I add to an array, it outputs the array index to the console. If anyone has tips of suppressing that, please let me know.
Code:
Param(
[Parameter(Mandatory=$true,Position=1)]
$pclist
)
"=================================================="
"PC Pinger"
"Will ping a list of PCs forever, output any good pings to a file"
"Usage .\pinger pclist"
"=================================================="
$d = Get-Date -Format o | foreach {$_ -replace ":", "."}
$outfile = $d + ".csv"
$infile = Get-Content $pclist
$servers = New-Object System.Collections.ArrayList
$removelist = New-Object System.Collections.ArrayList
$counter = 0
$goodcounter = 0
$alive
"==================================="
"Input List = $pclist"
"Output List = $outfile"
"==================================="
if (Test-Path $outfile) {"Deleting file $outfile"}
if (Test-Path $outfile) {Remove-Item $outfile}
#add PCs to array $servers from #infile
foreach($i in $infile) {
$servers.Add($i)
}
#The Main Loop - Will execute until Ctrl+C
while(1){
#Loop through the $servers list
foreach ($i in $servers) {
if ($counter -gt 10000) {$counter=0}
"Ping attempts: $counter Ping Success: $goodcounter"
$alive = Test-Connection -ComputerName $i -Count 1 -Delay 1 -TimeToLive 10 -Quiet
$counter++
#If PC pings, then add to file, and add to list to be removed, goodcounter++
if($alive) {
Add-Content -Path $outfile "$i,$alive"
$removelist.Add($i)
$goodcounter++
}
}
#Remove the object from the $servers array, then delete the $removelist
foreach ($i in $removelist) {$servers.Remove($i)}
$removelist = New-Object System.Collections.ArrayList
}