PowerShell script halts execution when Windows XP PC is locked

Posted by jshin47 on Server Fault See other posts from Server Fault or by jshin47
Published on 2012-06-07T15:59:08Z Indexed on 2012/06/07 16:42 UTC
Read the original article Hit count: 224

Filed under:

I have the following script that does a continuous ping and reports failures. It works fine, except the loop apparently "suspends" when the computer is locked. I have confirmed this by starting the script, immediately locking the PC, waiting 10 minutes, and seeing how many pings have occurred. It is nowhere near the expected number. What could be the culprit?

Write-Host "Entering monitoring loop..." -Background DarkRed

$ping   = new-object System.Net.NetworkInformation.Ping

$count_up  = 0
$count_dn  = 0
$count_dd  = 0

while ($true) {
    $result = $ping.send("10.1.1.1")

    if ($result.Status -eq "Success") {
        $count_up++
        $count_dd = 0
    }
    else {
        $count_dn++
        $count_dd++

        $this_date = Get-Date

        Write-Host "VPN ping failed at time " $this_date -Background Magenta

        if ($count_dd -gt 3) {
            Write-Host "***VPN is Down***" `a
            send_mail_notification("VPN is Down", "")
        }
    }

    if ($Host.UI.RawUI.KeyAvailable -and ("q" -eq $Host.UI.RawUI.ReadKey("IncludeKeyUp,NoEcho").Character)) {
        Write-Host "Exiting monitoring loop..." -Background DarkRed
        break;
    }

    Start-Sleep -m 250
}

$total = $count_up + $count_dn
$uptime = 100 * $count_up / $total

Write-Host $count_up " out of " $total " pings for a " $uptime "% uptime."

© Server Fault or respective owner

Related posts about powershell