PowerShell Get-ADUser "invalid enumeration context" and "unable to contact the server" errors
<p>First of all, this is the code I'm working on:</p>

<pre><code>function Scan-Homedirs
{
[CmdletBinding()]
PARAM ($SAN,$UserType)

switch ($UserType) {
    'Staff' { Import-Csv -Path '\\&lt;path&gt;\&lt;file&gt;.csv' `
                 | ? {$_.Type -eq 'Staff'} | % { $Path = "\\$($_.Server)\homedirs\$SAN"
                                                 if (Test-Path $Path) {
                                                    New-Object -TypeName psobject -Property ([ordered]@{SAN       = $SAN;
                                                                                                        Directory = $Path})
                                                    &lt;#(gci $Path -Recurse | Measure-Object -Property length -Sum).sum
                                                    (gci $Path -Recurse).Count#&gt; }
                                               }
            }

    'Student' { Import-Csv -Path '\\&lt;path&gt;\&lt;file&gt;.csv' `
                   | ? {$_.Type -eq 'Student'} | % { $Path = "\\$($_.Server)\Studirs\"
                                                     gci $Path | ? {$_.PSIsContainer} } | % { if (Test-Path "$Path$($_.Name)\$SAN") {
                                                               $Path = "$Path$($_.Name)\$SAN"
                                                               New-Object -TypeName psobject -Property ([ordered]@{SAN       = $SAN;
                                                                                                                   Directory = $Path})
                                                               &lt;#(gci $Path -Recurse | Measure-Object -Property length -Sum).sum
                                                               (gci $Path -Recurse).Count#&gt; }
                                                     }
              }
                   }
}

$DateMinus6Mo = (Get-Date).AddMonths(-6)
$Dirs = @()
Get-ADUser -ResultPageSize 100000 -Filter {(Enabled -eq 'False') -and (LastLogonDate -lt $DateMinus6Mo)} -Properties LastLogonDate,Description,Title | `
select Surname,GivenName,SamAccountName,Description,Title,LastLogonDate,Enabled | % {
    $Dirs = Scan-Homedirs "$($_.SamAccountName)" $_.Title
    if ($Dirs.Count -ne 0) {
        for ($i=0;$i -lt $Dirs.Count;$i++) {
            New-Object -TypeName psobject -Property ([ordered]@{SAN       = $_.SamAccountName;
                                                                Directory = $Dirs[$i].Directory})
        }
    }
    else { New-Object -TypeName psobject -Property ([ordered]@{SAN       = $_.SamAccountName;
                                                               Directory = "No directories found"})
    }
} | sort -Property SamAccountName | Export-Csv -Path '\\&lt;path&gt;\&lt;file&gt;.csv'
</code></pre>

<p>What I'm doing is querying AD to get all user accounts which are disabled and have a last logon date of 6 months ago or longer, piping the output to a function which scans all of our file servers for homedirs, then returns those results to the main script. I'm going to add another function to delete the homedirs, but need to make sure it's getting all of the accounts first. The code is working to give me the results I want as I've tested with small groups of data. It also works for a while when I comment out the last line to sort and export to csv, and writes the objects line by line to the console, but it eventually errors with "unable to contact the server", so it's like the pipeline can't handle that much data at once, or PowerShell can't, or something.</p>

<p>If I enable the sort and export to csv, initially I was getting the "invalid enumeration context" error and it referenced the <code>Get-ADUser</code> line, so I did some research and added the <code>-ResultPageSize</code> parameter and set it to 100000. Now I'm getting the <code>Get-ADUser : Unable to contact the server</code> error, which is strange because if it can't contact the server, why does it work at least in part when <code>Export-CSV</code> is commented out? It shouldn't be a permissions issue because I am running ISE with domain admin credentials, and all my other scripts which interact with AD work fine. </p>

<p>I then tried to run the script on a DC while logged on as my domain admin account, and the script runs but only for a few seconds and only returns 3 objects. I tried on another DC and got the same result. That's also strange because when running the script from my workstation, it runs for about 10 minutes until it errors out. </p>

<p>I suspect maybe it's because it needs to process over 4,200 user accounts. I verified this by running <code>(Get-ADUser -Filter {(Enabled -eq 'False') -and (LastLogonDate -lt $DateMinus6Mo)}).Count</code>, which also runs just fine and returns the appropriate number. Need some help getting this to work!</p>