Test and Restart Network Interface with PowerShell

I recently had a problem with the WiFi card in my laptop after running Windows Updates and updating the driver.  It would intermittently just drop the connection to the network (even though it’s sitting in the same room as the router) and I’d have to disable and re-enable the adapter to get connected again.

Ok, these things happen. I normally just rollback the driver (or search for a better one) and go about my merry life. But, this was the first time I’d had to rollback a driver in a while (since I upgraded to Windows 8, at least). I couldn’t quickly find (or remember) where to do it and I was in a rush – I needed to make sure that this computer was available for me to remote into while I was traveling later that day and I was heading out the door.

Side note: You rollback a driver through Device Manager, opening the properties for the adapter, and click “Roll Back Driver” on the Driver tab. Sure, now I remember.

So, I did a quick fix and wrote a script to test the network connectivity and restart the wireless adapter, if it couldn’t ping Google. I dropped it into into the Task Scheduler to run every 30 minutes and didn’t have to worry about it until I had time to fix the driver.

Unfortunately, the “NetAdapter” commands are only available in PowerShell 3.0 and above, but only on Windows 8 / Server 2012 and above. We’re out of luck with this particular script on Windows 7 and below.

But, in case it’s useful for anyone else, here is the script.  I have it logging to C:\Logs\, so that I can review how often it had to restart the adapter (the Start-Transcript and Stop-Transcript commands are your friend!).

Start-Transcript C:\Logs\RestartWiFi_$(Get-Date -Format "yyyyMMddHHmm").txt

$pingTest = ping www.google.com | Select-String "Reply from"

If ( $pingTest.count -eq 0 ) {
Writ-Output "[WARN] Ping test failed. Restarting Wi-Fi adapter."
Disable-NetAdapter "Wi-Fi" -Confirm:$false
Sleep 5
Enable-NetAdapter "Wi-Fi" -Confirm:$false
}
Else {
Write-Output "[INFO] Ping test successful. Exiting."
}

Stop-Transcript

Note that my wireless adapter’s name is “Wi-Fi” but yours may differ. To find the name of your network adapter, use the Get-NetAdapter command.

Leave a Reply