查找可用的驱动器号并更改

Find Available Drive Letter and Change

我正在尝试创建一个 PowerShell 脚本,它将找到一个可用的驱动器号,映射一个网络驱动器,然后更改为该映射的驱动器。我发现以下将 \server\share 映射为 D: 驱动器:

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

我可以手动输入 D:,但如何在脚本中更改它?我是这么想的:

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

但是上面的语句抛出以下错误:

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

您可以根据当前分配的驱动器号列表检查可能的驱动器号列表,并使用第一个未使用的驱动器号:

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

或该列表中的随机一个:

$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 的回答中使用的函数可能会返回 DVD/CD 驱动器,因为其中没有媒体。要获得一个免费的盘符,那是 likely* 而不是我们从 i-z[= 搜索的 CD/DVD 驱动器17=]: $dl=ls function:[i-z]: -n | ?{ !(test-path $_) } |select -last 1