Testing for Location on a Laptop

September 4th, 2016 by and tagged , ,

On my laptops, I have a different set of drive maps when I’m at home, or on the road. At home, I map to various local domain resources, but when I’m on the road, those resources aren’t available and I need to create “local” maps to versions that I can sync up to those domain resources when I get back home. But how to know where I am? Use PowerShell’s Test-Connection, of course, the PowerShell version of “ping”.


The problem is further complicated by the dual nature of my home network – I have two different subnets, and the resources could be reachable on either, depending on the wireless network to which I’m connected.


So, how to handle? I’ve chosen to use the logical OR operator for this test. I could have used an if {} elseif {} construction, but that seemed clunky, so I went with a simple test:

$AtHome= ((test-connection `
                           -Count 1 `
                           -TimeToLive 1 `
                           -quiet) `
         -OR (Test-Connection `
                           -count 1 `
                           -TimeToLive 1 `

The test tells me if my domain controller is reachable on either of the subnets used. Because PowerShell uses shortcut processing for logical operators, if the test succeeds at, it immediately returns $True to the $AtHome variable and doesn’t bother processing the second test. But if it fails the first test, it then tries the second subnet. If it can reach, it sets $AtHome to $True. If not, it sets $AtHome to $False.


Now, when I call my drive mapping script, and I pass it the result of $AtHome. That script knows to modify the behaviour based on the Boolean value of $AtHome…

Map-myDrive -SMB -AtHome $AtHome -Force

Posted in $Profile, PowerShell, Survival Guide | Comments Off on Testing for Location on a Laptop

Comments are closed.