Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

Find next available free drive letter using PowerShell

October 25, 2017 11:09AM

Below is my one-liner small PowerShell code for finding next available free unassigned first drive letter, I use it frequently for automating mapping shared drives. This is based on Get-PSDrive -PSProvider FileSystem, it shows the all in use drive, Generally A, B (floppy drive not for use as disk or mapped drive) and C are always in use on Microsoft OS as root drive, I am skipping those drive while checking. .Net Object [Char] used to represent a Unicode character, 68..90 represented to letters D..Z. This converted Unicode characters and Get-PSDrive is compared using If statement and shows the next available drive letter which does not exist or in use. Below is the one-liner main code.

1
(68..90 | %{$L=[char]$_; if ((gdr).Name -notContains $L) {$L}})[0]

Once I have result stored in $FreeDrive variable, I use it one of the in below example cmdlet for mapping remote shared drive. Also useful while automating new physical drive adding and assigning drive letter. (Alternative command for mapping shared drive is Net Use)
New-PSDrive -Name $FreeDrive -PSProvider FileSystem -Root '\\Server\c$' -Persist

Powershell find free available drive letter get-psdrive, char notcontains, New-PSDrive Psprovider root persist

Here it is another script I recently used to find last free drive letter on remote server for some re-purposing my further other script tools. This requires CIM cmdlets and available on Powershell version 4 and above and uses CIMClass win32_LogicalDisk to get list of drive letter from remote machine. Copy paste script in PowerShell $PROFILE file.

Code given above can also be used using my earlier article POWERSHELL PS REMOTING BETWEEN STANDALONE WORKGROUP COMPUTERS 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
Function Search-FreeDriveLetter {
    [CmdletBinding(SupportsShouldProcess=$True,
        ConfirmImpact='Medium',
        HelpURI='http://vcloud-lab.com')]
    Param
        ( 
            [String[]]$ComputerName = $env:COMPUTERNAME,
            [ValidateSet('Dcom', 'WSman', 'Default')][String]$Protocol = 'Dcom'
        )
    Begin {
        #$Protocol = 'Dcom'
        #$ComputerName = $env:COMPUTERNAME
        $CimOption = New-CimSessionOption -Protocol $Protocol
        $AllDriveLetters = 90..68
        $Credential = Get-Credential
    }
    Process {
        foreach ($Computer in $ComputerName) {
            try {
                $CimSession = New-CimSession -Name $Computer -SessionOption $CimOption -Credential $Credential -ErrorAction Stop
            }
            catch {
                Write-Host "Connecting $computer failed ..." -BackgroundColor DarkRed
            }
            $CurrentDriveLetters = Get-CimInstance -ClassName Win32_LogicalDisk -CimSession $CimSession
            ForEach ($SingleDriveLetter in $AllDriveLetters) {
                $D2ZLetter = [String][Char]$SingleDriveLetter
                $TestDriveLetter = "{0}:" -f $D2ZLetter
                $ListCheck = $CurrentDriveLetters.DeviceID -contains $TestDriveLetter
                $TestPath = Test-Path $TestDriveLetter
                If ($ListCheck -eq $false -and $TestPath -eq $false) {
                    $TestDriveLetter
                    Break
                }
            }
        }
    }
}

After Executing Search-FreeDriveLetter Machine01, Machine02, it will prompt for username and password to connect remotely. This script I used in VMware infrastructure where I wanted to initialize and add disk in VMs.

Powershell search-freeDriveLetter free drive find ciminstance, cimsession, get-ciminstance, cimsessionoption cim cmdlet

Useful Articles
Powershell Active Directory: Show treeview of User or Group memberof hierarchy ##How to use $PROFILE to store function
Different ways to bypass Powershell execution policy :.ps1 cannot be loaded because running scripts is disabled
Installing, importing and using any module in powershell

Go Back

Comment