Advertisement
Yevrag35

Test All DC Ports Async

Oct 26th, 2020 (edited)
4,403
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $list = New-Object System.Collections.Generic.List[object](4)
  2. $maxRunspaces = 20
  3. $servers = Get-ADDomainController -Filter *
  4. $testPorts = @(389, 636, 3268, 3269)
  5.  
  6. # Set up the runspace pool and powershell script
  7. $rsPool = [runspacefactory]::CreateRunspacePool(1, $maxRunspaces)
  8. $rsPool.ApartmentState = "STA"
  9. $rsPool.ThreadOptions = "ReuseThread"
  10. $rsPool.Open()
  11. $code = {
  12.     param ($Server, $Port)
  13.  
  14.     Test-NetConnection -ComputerName $Server -Port $Port
  15. }
  16.  
  17. # Add a runspace'd powershell instance for every server on each specified port
  18. foreach ($s in $servers) {
  19.  
  20.     foreach ($port in $testPorts) {
  21.  
  22.         $psInst = [powershell]::Create().AddScript($code).AddParameter("Server", $s.HostName).AddParameter("Port", $port)
  23.  
  24.         $psInst.RunspacePool = $rsPool
  25.  
  26.         $list.Add([pscustomobject]@{
  27.             PowerShell = $psInst
  28.             Runspace = $psInst.BeginInvoke()
  29.         })
  30.     }
  31. }
  32.  
  33. $allResults = New-Object System.Collections.Generic.List[psobject]($servers.Count * 4)
  34.  
  35. # As long as there is one job still left in the list, keep looping and checking for completed jobs.
  36. # Add the results from each job into a final list.
  37. while ($list.Count -gt 0) {
  38.  
  39.     for ($i = $list.Count - 1; $i -ge 0; $i--) {
  40.  
  41.         $job = $list[$i]
  42.         if ($job.Runspace.IsCompleted) {
  43.  
  44.             $results = $job.PowerShell.EndInvoke($job.Runspace)
  45.             $job.PowerShell.Dispose()
  46.             [void] $list.Remove($job)
  47.             if ($results.Count -gt 0) {
  48.  
  49.                 $allResults.AddRange($results)
  50.             }
  51.         }
  52.     }
  53.     Start-Sleep -Milliseconds 200
  54. }
  55. $allResults
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement