Home > Enterprise >  How to log out of PC if wifi network is not detected?
How to log out of PC if wifi network is not detected?

Time:04-23

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

CodePudding user response:

It has been done for you, though using Bluetooth:

Lock your Windows PC automatically when you step away from it

CodePudding user response:

As codaamok mentions in the comments, you can use Get-NetAdapater which, lucky for us, has a Status property that shows the devices Network Status; so, if it's on it will show "connected", and when off it shows "disconnected".

while ($true) {
    Start-Sleep -Seconds 10
    $adapter = Get-NetAdapter -Name "Wi-Fi 2" 
        if ($adapter.Status -eq "Disconnected") {
            Write-Output -InputObject ($adapter.Name   " "   $adapter.Status)
            break #Or just invoke logoff.exe
            #logoff
        }
}

You want that Start-Sleep with a preferably longer delay so it doesn't continuously make a call to Get-NetAdapter leading 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 while loop has a condition of $true that will make it run indefinitely until the loop is broken out of. After the Start-Sleep (explained above), a call to Get-NetAdapter is made which is then saved to $adapter. Finally, using an if statement, we just check to see if the property Status has a value of "Disconnected" and if so, break the loop, or just invoke logoff.exe.

  • Related