我正在尝试创建一个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
答案 0 :(得分:1)
您可以针对当前分配的驱动器号列表检查潜在驱动器号的列表,并使用第一个未使用的驱动器号:
$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}:"
答案 1 :(得分:0)
Ansgar的答案中使用的功能可能会返回DVD / CD驱动器,因为它没有媒体。要获得免费的驱动器号, 可能* ,而不是我们从 i-z 搜索的CD / DVD驱动器:
$dl=ls function:[i-z]: -n | ?{ !(test-path $_) } |select -last 1