I have an idea for a script I am trying to write. Essentially I want my computer to logoff if it does not detect the hotspot from my phone. If I were to walk away from my computer I'd want it to automatically log off if I got too far away. The code snippet down below does work, unfortunately when I disable my hotspot it still shows up as an available network until I turn my PC's wifi on and off. Is there a way I can refresh that list or something in powershell? Any other potential ideas to make this work?
try {
$SSID = "Phone"
$Network = (netsh wlan show networks mode=Bssid | ?{$_ -like "SSID*$SSID"}).split(':')[1].trim()
if ($Network) { Write-Host "The SSID is detected" }
}
catch {
shutdown -L
}
I did just see that someone potentially found a way to do it wuth a vbs script but I have not been succseful in making it work, but I'll leave the code down below for anyone to tinker with.
Sub ClickIt()
With CreateObject("WScript.Shell")
.Run "%windir%\explorer.exe ms-availablenetworks:"
End With
End Sub
As codaamok mentions in the comments, you can use
Get-NetAdapaterwhich, lucky for us, has aStatusproperty that shows the devices Network Status; so, if it's on it will show "connected", and when off it shows "disconnected".You want that
Start-Sleepwith a preferably longer delay so it doesn't continuously make a call toGet-NetAdapterleading to some memory consumption. Honestly, you may want this in a Scheduled Task instead which is the route I would take here.As for the code: The
whileloop has a condition of$truethat will make it run indefinitely until the loop is broken out of. After theStart-Sleep(explained above), a call toGet-NetAdapteris made which is then saved to$adapter. Finally, using anifstatement, we just check to see if the propertyStatushas a value of "Disconnected" and if so, break the loop, or just invoke logoff.exe.