Enumerating Drive Letters

Share |

Join PowerShell.com!
Subscribe to Feed

PowerShell eBook
Sign up for
Your PowerTip of the Day:

Award-winning PowerShellPlus


Admin Guide to PowerShell Remoting


Mastering PowerShell eBook

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]

Posted Jan 15 2009, 08:00 AM by ps1

Comments

Sylvain LESIRE wrote re: Enumerating Drive Letters
on 01-16-2009 3:18 AM

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

replace 89 by 90

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

find a solution by using WMI

$letters = Get-WmiObject win32_logicaldisk -computername . | select deviceID,drivetype,description

Sylvain LESIRE wrote re: Enumerating Drive Letters
on 02-24-2009 3:01 PM

An other way to enumerate drive

get-psdrive | Where-Object {$_.Provider -match "filesystem"}

Modify disk layout in Windows using powershell « The Admin Guy’s Blog wrote Modify disk layout in Windows using powershell « The Admin Guy’s Blog
on 11-08-2009 6:20 PM

Pingback from  Modify disk layout in Windows using powershell « The Admin Guy’s Blog

Modify Disk layout in Windows using powershell – updated version « The Admin Guy’s Blog wrote Modify Disk layout in Windows using powershell – updated version « The Admin Guy’s Blog
on 11-13-2009 5:24 PM

Pingback from  Modify Disk layout in Windows using powershell – updated version « The Admin Guy’s Blog

Copyright 2012 PowerShell.com. All rights reserved.