Home > Microsoft, Powershell > PowerShell: Finding next available driveletter

PowerShell: Finding next available driveletter

Finding the next available driveletter on a system, excluding reserved driveletters, can be done using the following PowerShell 1-liner.

[char[]]”DEFGJKLMNOPQRTUVWXY” | ?{!(gdr $_ -ea ‘SilentlyContinue’)} | select -f 1

The character array containing only valid driveletters (in this example A, B, C, H, I, S and Z are not to be used)  is piped to the where-object cmdlet which uses Get-PSDrive to filter out the non-used drive letters. These are then passed to the Select-Object cmdlet which only displays the 1st match.

Beware: the line above returns only the bare driveletter – no colon is appended.

  1. Stephen Mills
    July 2nd, 2009 at 01:17 | #1

    Your script actually will include optical drives that don’t currently have media inserted. Here’s a variation that does work however. This includes the drive letters C-Z.
    [char[]]’CDEFGHIJKLMNOPQRSTUVWXYZ’ | ? { (Get-PSDrive $_ -ErrorAction ‘SilentlyContinue’) -eq $null }

  2. Hans
    July 2nd, 2009 at 08:02 | #2

    Thanks Stephen.

    This is the result of a sloppy cut/paste action. I modified the post now using the correct cmdlet etc.

  1. No trackbacks yet.