Mapping Drives

January 3rd, 2012 by and tagged , ,

My standard environment expects to have several drive mappings wherever I’m logged in to my network. Even when I’m running on a computer that isn’t joined to the domain. To facilitate that, I have a simple “mapdrives.cmd” file that has the necessary net use commands in it to map them.  Then my default PowerShell $profile calls mapdrives.cmd. This works well, except that the result is fairly messy if there’s a problem.

Problem? Sure. For example, if my laptop isn’t in the office, then it won’t be able to map the drives on my office network. Or, if the dries are already mapped as part of a group policy, I’ll get an error when I try to map them. So, I decided to get smarter about it. Here’s the relevant section of my $profile:

$InOffice = test-connection -quiet
$isMapped = Get-WMIObject -query “Select * from Win32_LogicalDisk where DeviceID=’A:'”
if ($InOffice -and ! $isMapped ){
if ($maps) {& $maps }

Now there may be even better ways to do this, but for me this works well. The $InOffice test checks for the presence of a server that should be reachable if I’m in the office, but that will not be reachable anywhere else. The $isMapped test checks to see if one of my standard drive mappings has already been done.

The result? If I’m not in the office, it won’t bother mapping drives and thus save some significant startup time while it tried to map them and then failed. And if I’m in the office, but they’ve already been mapped, it won’t bother either, saving no time but keeping my PowerShell window from echoing all those errors as it tries to map something that is already mapped.

Find this useful? Got a better way to do it? Leave a comment, please.



ETA: Yech, boy was this ugly back then. But now we have many new features in PowerShell v5, so I’ve updated things a bit. See my Mapping Drives Revisited post for a much better way to do this.

Posted in PowerShell | Comments Off on Mapping Drives

Comments are closed.