简体   繁体   中英

How to assign available driveletter by mapping type name using powershell?

I would like to assign a driveletter to a specific volume. But I don't know which driveletter is availabel, so I use looping to check available letter. I tried this way but it always return to input partition number.

$DriveLetterList = 90..65 | ForEach-Object {[char]$_ }
foreach($list in $DriveLetterList){
   $Get = Get-Partition | Where-Object{$_.Type -eq "Recovery"} | Set-Partition $list
   if ($null -eq $Get) {
         Start-Sleep -s 1
         $n = 0
         while ($null -ne $Get) {
            $n++
            Break
      }
   }
}  

Anyone can help me with this really appreciate. Thank you so much

You can simplify it a lot it seems, you just need to get all partitions first and then filter where the array chars are not in the array of used letters. From there it's just get the Recovery partition and setting a new letter to it.

I'm using | Select-Object -First 1 | Select-Object -First 1 to pick the first available char, however, you could change it to | Get-Random | Get-Random to pick a random available char.

$partitions = Get-Partition
$newLetter  = [char[]] ([char]'A'..[char]'Z') |
    Where-Object { $_ -notin $partitions.DriveLetter } |
    Select-Object -First 1

$partitions | Where-Object { $_.Type -eq "Recovery" } |
    Set-Partition -NewDriveLetter $newLetter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM