#PSTip Get next available drive letter

Mapping drives is a routine task for IT pros—you choose a free drive letter, ranging from A-Z, and then use it to map a drive to a specific path. What if you need to do that in a script? How do you know which letter is available for the new drive?

Here at the magazine we dedicated a Brain Teaser to find an unused drive letter but we want to tell you of another, new, built-in way to get that information.

Windows 8 and Server 2012 ship with the Storage module which provides PowerShell cmdlets for end to end management of Windows storage. One of the module functions is Get-AvailableDriveLetter.

Update (8/20/2012)
In Windows 8 RTM, Get-AvailableDriveLetter is not a part of the Storage module.
However it will be included in a downloadable module at the TechNet Script Center in the near future.
In the meantime, you can put the code in your own Get-AvailableDriveLetter function.

Running the function without any parameters outputs all available drive letters:

PS> Get-AvailableDriveLetter


We can also ask for the first letter only:

PS> Get-AvailableDriveLetter -ReturnFirstLetterOnly

Finally, since this is a function, we can see how letters are retrieved by taking a look at the function definition:

PS> Get-Command Get-AvailableDriveLetter | Select-Object  –ExpandProperty Definition


	$volumeList = Get-Volume
	# Get all available drive letters, and store in a temporary variable.
	$UsedDriveLetters = @(Get-Volume | % { "$([char]$_.DriveLetter)"}) + @(Get-WmiObject -Class Win32_MappedLogicalDisk| %{$([char]$_.DeviceID.Trim(':'))})
	$TempDriveLetters = @(Compare-Object -DifferenceObject $UsedDriveLetters -ReferenceObject $( 67..90 | % { "$([char]$_)" } ) | ? { $_.SideIndicator -eq '<=' } | % { $_.InputObject })

	# For completeness, sort the output alphabetically
	$AvailableDriveLetter = ($TempDriveLetters | Sort-Object)
	if ($ReturnFirstLetterOnly -eq $true)

For a list of the cmdlets contained in the Storage module, see the following topic on TechNet

Filed in: Columns, Tips and Tricks Tags: ,
© 2018 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: