Get First Available Drive Letter

What does this do?: To make things short, the title says it all. This function gets the first available drive letter.

Function Get-NxtDriveLett {
    #Gets the drive letters that already exist on the system
    $Letters = Get-WMIObject Win32_LogicalDisk | Select -Expand DeviceID  | ForEach {$_[0]}

    #Stores the first driver letter as an Integer
    $TestLetters = [Int][Char]$Letters[0]

    #Tests each letter and finds the next available letter and converts it back into a Character
    ForEach ($Letter in $Letters) {
        If ([Int][Char]$Letter -ne $TestLetters) {
            $AvailLetter = [Char]$TestLetters
            Break
        }
        $TestLetters+=1    
    }

    #Displays the next available drive letter
    $AvailLetter
}

Example: Creating an automated DiskPart script.

$usbLetter = Get-NxtDriveLett
$selectedDisk = #Index Number of Drive

#Holds the commands that diskpart will use
$commands=@(
    "select disk $selectedDisk",
    "clean",
    "create partition primary",
    "format fs=NTFS quick",
    "assign letter=$usbLetter",
    "active"
)

#Pipes the commands into diskpart
$commands | diskpart

Why I needed this Function: Was writing a script to automatically create a Win7 x64/x86 bootable USB disk. The script begins with asking which USB disk the user wants to use for the process. It then asked which OS type to use (x64/x86). Then the automation begins. It finds the next available drive letter and passes the information through DiskPart like in the example above. It changes the label of the drive to either Win7x64 or Win7x86, depending on the OS that was chosen. Lastly, it copies pre-extracted ISO files from a shared drive across the network to the root of the USB drive.

I found it very useful for the script to be able to locate the next available drive letter instead of me looking through all of my drives and singing the ABC’s in my head to identify the next drive letter and then taking the time to type that letter into the console. Come on, this is 2016! Automation people!

-Andrew

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s