Search code examples
powershelldictionarynetwork-programmingsharedrive

How to map multiple share drives upto 22 at a time using powershell?


I have about 9000 DFS share drives in my environment. Unfortunately since there is no easy way to find out the size of each share drive with powershell i am trying to map 22 at a time and save the dump the results to csv file So i am trying something like this

$csv=Import-Csv "path"
$csv.Name
foreach-object{
New-PSdrive -Root $_ -Name $driveletter}

The issue is that i need to start at drive letter E and go all the way to Z, obtain the drive size, unmap the current 22 drives and and then go to the next 22 and so on until the 2500th path Is there an easy way to do this?


Solution

  • Here's a possible solution for what you ask (although per the comments it would be simpler to just use the same drive letter repeatedly, however this might be faster):

    Function CleanUp-PSDrive {
        Get-PSDrive -PSProvider FileSystem | Where { $_.Name -in (69..90 | ForEach-Object { [char]$_ })} | Remove-PSDrive
    }
    
    $Csv = Import-Csv "path"
    
    $Csv.Name | ForEach-Object -Begin { $Letter = 69 } {
    
        New-PSdrive -Root $_ -Name ([char]$Letter) -PSProvider FileSystem
    
        #Do some stuff..
    
        if ($Letter -lt 90) 
        { 
            $Letter++ 
        } 
        else 
        { 
            CleanUp-PSDrive
            $Letter = 69
        }
    } -End { CleanUp-PSDrive }
    

    This uses the ASCII codes for E - Z (69 - 90) to create the lettered drives as it iterates through your CSV, when we get to letter 90 (Z) it removes all the drives using a function I declared called CleanUp-PSDrive and then sets $Letter to start over at 69 (E).

    I created the CleanUp-PSDrive function because I realised that you'd need to do a clean up after the final iteration of an unknown number of remaining mapped drives. The function does this by getting them dynamically with Get-PSDrive. We then use the -End block of ForEach-Object to do this final cleanup.

    I use the -Begin block of the ForEach-Object to declare $Letter for no other reason than it connects it nicely to where the counter is used.