Dealing with drive letters in PowerShell

Have you ever wondered why the newly installed disk gets a drive letter in the middle of the alphabet even though E: is free? Why that network drive refuses to connect with the drive letter you want? The reason is most probably that the drive letter you want has been reserved for removable drives even though no media is inserted. This has been an problem for some time now since many computers are shipped with built-in multimedia card readers.

W8-storage-management

In the above example, if you for example try to map a network drive as F: it will fail because it is already reserved by a SD card reader, even when no card is inserted. The solution: change the drive letters to something that you know will never conflict.

Here’s a PowerShell script that automatically reassigns drive letters on removable drives to a predefined set of “approved” drive letters. The script uses the standard mountvol tool, so it also works in older Windows versions.

Replace-DriveLetters.ps1

$ForbiddenDrives = @("E:","F:","G:","H:")
$AllowedDrives = @("W:","X:","Y:","Z:")

$RemovableDrives = Get-WmiObject -Class Win32_Volume -Filter "DriveType=2"
$DrivesToReassign = $RemovableDrives | Where-Object { $ForbiddenDrives -contains $_.DriveLetter }
$i=0

foreach ($Drive in $DrivesToReassign) {
     &mountvol $Drive.DriveLetter /D
     &mountvol $AllowedDrives[$i++] $Drive.DeviceID
}

In an Enterprise Environment this is easy to implement in for example Microsoft Deployment Toolkit. That way your clients will never fail mapping network drives.

MDT

/ Andreas

Advertisements

3 thoughts on “Dealing with drive letters in PowerShell

  1. Gary Wertman

    Any chance you’d know why this script would result in the verbose output of the mountvol command? Thanks! 🙂

    Reply
    1. Andreas Lindahl Post author

      To remove the output from the command the best way is to pipe the output into the Write-Verbose cmdlet. That way you can use the code, and build your own functions that accepts the -Verbose parameter to see the output.

           &mountvol $Drive.DriveLetter /D | Write-Verbose
           &mountvol $AllowedDrives[$i++] $Drive.DeviceID | Write-Verbose
      
      Reply
      1. Gary Wertman

        Thanks Andreas! In this case the script was giving the mountvol syntax because it had nothing to do – and that was due to my failure to supply the correct forbidden drives. 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s