Enumerating Drive Letters

by Jan 15, 2009

Sometimes, you may want to find the next available drive letter for a network drive or enumerate drive letters for other purposes. An easy way to create an array with drive letters is this:

$letters = 65..89 | ForEach-Object { ([char]$_)+":" }

$letters now is a string array with all available drive letters. Use Test-Path to see whether the drive exists and return the first unassigned drive letter:

$letters | Where-Object { (!(test-path $_)) }

Unfortunately, this approach is error prone because test-path will report the drive letters of CD/DVD-Drives without a medium as available. The right way of doing it is using .NET:

$letters | Where-Object { 
(New-Object System.IO.DriveInfo($_)).DriveType -eq 'NoRootDirectory'
}

Now you get back all drive letters that are currently unused. To get only the first available letter, access the first array element:

@($letters | Where-Object { 
(New-Object System.IO.DriveInfo($_)).DriveType -eq 'NoRootDirectory'
})[0]