Brian Weaver
Brian Weaver

Reputation: 41

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

Upvotes: 1

Views: 2861

Answers (2)

Hedgehog
Hedgehog

Reputation: 5657

The functions used in Ansgar's answer are likely returning the DVD/CD drive because it has no media in it. To get a free drive letter, that is likely* not the CD/DVD drive we search from i-z: $dl=ls function:[i-z]: -n | ?{ !(test-path $_) } |select -last 1

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200503

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}:"

Upvotes: 2

Related Questions