Getting a free drive letter

后端 未结 11 453
青春惊慌失措
青春惊慌失措 2020-12-10 13:40

I saw the Get-NextFreeDrive function in this answer and I wondered if there was a more efficient way to do this. It appears that the function in the linked answ

相关标签:
11条回答
  • 2020-12-10 14:13

    Another way...

    $DriveList = Get-PSDrive -PSProvider filesystem | foreach({($_.Root).Replace(":\","")})
    $AllDrives = [char[]]([int][char]'E'..[int][char]'Z')
    $NextDriveLetter = ($AllDrives | Where-Object { $DriveList -notcontains $_ } | Select-Object -First 1) + ":"
    
    0 讨论(0)
  • 2020-12-10 14:15

    I found out that Test-Path evaluates my empty CD-Drive as False, here is another alternative that will compare every letter in the alphabeth until it finds one that doesn't exist in filesystem, then returns that drive as output.

    $DriveLetter = [int][char]'C'
    WHILE((Get-PSDrive -PSProvider filesystem).Name -contains [char]$DriveLetter){$DriveLetter++}
    Write-Host "$([char]$Driveletter):"
    
    0 讨论(0)
  • 2020-12-10 14:16
    $taken = Get-WmiObject Win32_LogicalDisk | Select -expand DeviceID
    $letter = 65..90 | ForEach-Object{ [char]$_ + ":" }
    (Compare-Object -ReferenceObject $letter -DifferenceObject $taken)[1].InputObject
    

    Just for fun to shave an extra line of code (lol). If you wanted to be cloppy as heck you could skip instantiating variables and just pipe those directly into -Ref and -Diff directly, probably ought to be slapped for doing that though. :)

    Selects [1] to avoid getting the A: drive just in case that might complicate matters.

    0 讨论(0)
  • 2020-12-10 14:18

    At PowerShell Magazine, we ran a brain teaser contest to find out the shortest answer to your question. Check this:

    http://www.powershellmagazine.com/2012/01/12/find-an-unused-drive-letter/

    There are several answers but here is my fav one:

    ls function:[d-z]: -n | ?{ !(test-path $_) } | random
    
    0 讨论(0)
  • 2020-12-10 14:22

    I had to Write a function that works with Powershell V2.0. The following Function will Return the next available letter, it also can get an exclude letter as parameter:

    Function AvailableDriveLetter ()
    {
    param ([char]$ExcludedLetter)
    $Letter = [int][char]'C'
    $i = @()
    #getting all the used Drive letters reported by the Operating System
    $(Get-PSDrive -PSProvider filesystem) | %{$i += $_.name}
    #Adding the excluded letter
    $i+=$ExcludedLetter
    while($i -contains $([char]$Letter)){$Letter++}
    Return $([char]$Letter)
    }
    

    Let's say Your OS reports drive-letters C:,E:,F: and G: as being used.

    Running: $First = AvailableDriveLetter ,Will result in $First containing 'D'

    Running: $Sec = AvailableDriveLetter -ExcludedLetter $First ,Will result in $Sec containing 'H'

    0 讨论(0)
提交回复
热议问题