PowerShell Script to Dynamically Map a Free Drive Letter

In case when you need to map a local path as a new drive at a runtime, you need to determine which letter is free for use as a next drive letter. Here is a simple code that does this:

foreach ($letter in [char[]]([char]’A’..[char]’Z’)) {
    $drive = $letter + ‘:’
    if (!(Test-Path -path $drive)){
        break
    }
}

SUBST $drive "C:TempUser1Data"

 

For a descending order of processing change the alphabets series as below in foreach loop

foreach ($letter in [char[]]([char]’Z’..[char]’A’)) {

 

This can be a usual case for virtualized environments where you support mapping client devices as drives in the session as well as need to create a new drive with a free letter name dynamically.

Leave a Reply

Your email address will not be published. Required fields are marked *