1

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
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Brian Weaver
  • 41
  • 1
  • 2
  • 4

2 Answers2

2

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}:"
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • Thank you very much for your reply Ansgar. Both examples execute as you described. What I was hoping to do was be able to call this drive letter in a script. In your first example, the Z: drive is mapped on my computer. How can I call that in a script? I can manually type "Z:" to change the drive, but is there a way to change the drive by calling the variable $drive? – Brian Weaver Oct 11 '15 at 14:05
  • @BrianWeaver Use [`Set-Location`](https://technet.microsoft.com/en-us/library/hh849850.aspx) to change drive and/or folder. See updated answer. – Ansgar Wiechers Oct 12 '15 at 07:27
  • Thank you very much Ansgar! This is exactly what I needed. Your help is greatly appreciated. – Brian Weaver Oct 13 '15 at 12:01
0

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

Hedgehog
  • 5,487
  • 4
  • 36
  • 43