Testing for Location on a Laptop

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 192.168.16.2 `
                           -Count 1 `
                           -TimeToLive 1 `
                           -quiet) `
         -OR (Test-Connection 192.168.17.2 `
                           -count 1 `
                           -TimeToLive 1 `
                           -quiet)
        )

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 192.168.16.2, 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 192.168.17.2, 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

Leave a Reply

Your email address will not be published. Required fields are marked *