I wrote this PowerShell function to change drive letters with PowerShell and DiskPart. Other methods posted online utilize the Win32_Volume WMI class which is not available in Windows XP. Using DiskPart makes the function compatible with Windows XP/2003 as well as Vista/2008/7.

Also, note the method used to detect whether or not a drive exists. I use this method vs. Test-Path as Test-Path can return (what I consider) False-Falses. If you run Test-Path on a CD-ROM or other drive letter without any media, it will return False even though the drive letter itself is in use.

1
2
3
4
5
6
7
8
9
10
11
12
13
function ChangeDriveLetter($Current, $New){
 $CurrentDrive = New-Object System.IO.DriveInfo($Current)
 $NewDrive = New-Object System.IO.DriveInfo($New)
 
 if (($CurrentDrive.DriveType -ne "NoRootDirectory") -and ($NewDrive.DriveType -eq "NoRootDirectory")){
  Write-Host("Changing drive letter from " + $Current + " to " + $New + "...")
  "select volume " + $Current + [char]13 + [char]10 + "assign letter " + $New | diskpart > $Null
  Return $True
 } else {
  Write-Error("Can not change drive letter.  Either " + $Current + ":\ doesn't exist or " + $New + ":\ already exists.")
  Return $False
 } 
}
  • http://ad-powershell-blog.blogspot.com Scottie

    Hi Gregory,

    I happened to chance upon your blog and thought I’d say Hello. I work on the IT management (AD) side of the hosue and every now and then share my 2c on Powershell for Active Directory.

    Thought I’d drop by and say hello. Thanks for sharing the above snippet for others to use as well. If you’re looking for some info on PS for AD, don’t hesitate to stop by.

    Cheers,
    Scottie

   
© 2011 Gregory Strike (BETA) Suffusion theme by Sayontan Sinha