powershelldrive-letter

Find Available Drive Letter and Change


I am trying to create a PowerShell script that will find an available drive letter, map a network drive, and then change to that mapped drive. I found the following which mapped \\server\share as the D: drive:

$Drive = New-PSDrive -Name $(for($j=67;gdr($d=[char]$J++)2>0){}$d) -PSProvider FileSystem -Root \\server\share\

I can manually enter D:, but how can I change this in a script? I was thinking along the lines of this:

$Drive = $Drive.Trim(":")

But the statement above throws the following error:

Method invocation failed because [System.Management.Automation.PSDriveInfo] does
not contain a method named 'Trim'.
At line:1 char:1
+ $Drive = $Drive.Trim(":")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

Solution

  • You could check a list of potential drive letters against the list of currently assigned drive letters and use the first unused one:

    $used  = Get-PSDrive | Select-Object -Expand Name |
             Where-Object { $_.Length -eq 1 }
    $drive = 90..65 | ForEach-Object { [string][char]$_ } |
             Where-Object { $used -notcontains $_ } |
             Select-Object -First 1
    
    New-PSDrive -Name $drive -PSProvider FileSystem -Root \\server\share
    
    Set-Location "${drive}:"
    

    or a random one from that list:

    $used   = Get-PSDrive | Select-Object -Expand Name |
              Where-Object { $_.Length -eq 1 }
    $unused = 90..65 | ForEach-Object { [string][char]$_ } |
              Where-Object { $used -notcontains $_ }
    $drive  = $unused[(Get-Random -Minimum 0 -Maximum $unused.Count)]
    
    New-PSDrive -Name $drive -PSProvider FileSystem -Root \\server\share
    
    Set-Location "${drive}:"