1

i have a problem with code:

 Measure-Command{ $controller=Get-ADDomainController -Filter *| Select -ExpandProperty Hostname   
$users=Get-ADUser -Filter * |select samaccountname
$scriptblock={
    param($samacc,$controller)
    $result=@()
    foreach($cont in $controller){
    $RESULT=$result + (Get-ADUser -Server $cont -Identity $samacc -Properties lastlogon,whenchanged,displayname,title,company  | sort-object lastLogon -descending | select-object enabled,displayname,samaccountname,title,company, @{Name="lastLogon";Expression={[datetime]::FromFileTime($_.'lastLogon')}},whenchanged)
    }
    $result|Sort-Object -Descending -Property LastLogon|select -First 1
    }

$MaxThreads = 5
$RunspacePool = [runspacefactory]::CreateRunspacePool(1, $MaxThreads)
$RunspacePool.ApartmentState = "MTA"
$job=@()
$RunspacePool.open()
    foreach($user in $users){
    $PowerShell = [powershell]::Create().AddScript($scriptblock).AddArgument($user.samaccountname).AddArgument($controller)
    $PowerShell.RunspacePool = $RunspacePool
    $job+=[PSCustomObject]@{
        Id = $_
        Pipe = $PowerShell
        Handle = $PowerShell.BeginInvoke()
        Object = $Object
     }
    }
    while ($job.Handle -ne $null){
    $Completed = $job | Where-Object { $_.Handle.IsCompleted -eq $true }
        foreach ($Runspace in $Completed){
        $data=$Runspace.Pipe.EndInvoke($Runspace.Handle)
        $data|Export-Csv d:\fulllist.csv -Append -Delimiter ';' -Encoding UTF8 -NoTypeInformation
        $Runspace.Handle = $null       
        }
    Start-Sleep -Milliseconds 100
    }
    $PowerShell.Dispose()      
    $RunspacePool.Dispose()
    Remove-Variable controller,users,scriptblock,job,Completed,data,Runspace,RunspacePool,PowerShell
    [System.GC]::Collect()  
    }

I create for each user instance with powershell command, and throw it to runspacepool. But i have about 35000 users and when i reach about 18000 for me start problem with connection\session. And to result table get only data for 22000 users. Powershell then dont free memory. How can i correctly manage close instances to free memory (for users that already write to file).May be i use wrong place for commands or wrong commands.

Vad
  • 693
  • 3
  • 13

0 Answers0