Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a free drive letter

Tags:

powershell

I saw the Get-NextFreeDrive function in this answer and I wondered if there was a more efficient way to do this. It appears that the function in the linked answer keeps going through all the letters even if it has already found a free drive letter.

like image 820
Nick Avatar asked Sep 19 '12 03:09

Nick


People also ask

How can I get a free letter of drive?

Launch Regedit, navigate to HKEY_LOCAL_MACHINE\SYSTEM\MountedDevices. Check whether there is a device is shown as being mounted at the specific drive letter. 2>. Then, right-click the drive letter that you want and choose Rename from the list menu, and change the letter to any other used letter to free up it.

How do I get my drive letter back?

1] Manually Show Missing Drive LettersFrom the Start search, open Folder Options and click the 'View' tab. Scroll down the list of options until the 'Show drive letters' option is seen. Simply check the box marked against this option. Click 'Apply', then 'OK'.

How do I fix the specified drive letter is not free to be assigned?

You have to rename the current F drive letter to an unused letter. That frees up the letter you want to use. Use Disk Management to change it. Warning-- this will cause the same problem you are having now and will break connections to programs on the changed drive/partition.

What happens if you run out of drive letters?

Once you run out of drive letters Windows will force you to mount drives to a NTFS folder or mount points rather than a drive letter.


1 Answers

Here's what I came up with. I need the last available drive letter from A to Z.

$AllLetters = 65..90 | ForEach-Object {[char]$_ + ":"}
$UsedLetters = get-wmiobject win32_logicaldisk | select -expand deviceid
$FreeLetters = $AllLetters | Where-Object {$UsedLetters -notcontains $_}
$FreeLetters | select-object -last 1
  • This gets an array of letters A..Z
  • Then gets an array of the letters already in use from WMI
  • Next produces an array of letters not in use using the comparison operator -notcontains
  • Finally outputs a single letter.
like image 86
dliverpool Avatar answered Oct 02 '22 15:10

dliverpool