Trying to multithread some of my scripts that take a while to run. One example is getting the last login for a user. It checks all of our DC's and then returns the most recent time. We have quite a few and they are global so running sequentially takes a while.
I saw this answer How do I run my PowerShell scripts in parallel without using Jobs?
which got me going in setting up the runspace and running it but I am not sure how to get the data back.
This is what I have so far
$username = Read-Host "Enter the Users ID"
$dcs = Get-ADDomainController -Filter {Name -like "*"} | Select -expandproperty name
$Code = {
Param($username,$dc)
Get-ADUser $username | Get-ADObject -Server $dc -Properties lastLogon |
Select -Expandproperty lastLogon
}
$rsPool = [runspacefactory]::CreateRunspacePool(1,8)
$rsPool.Open()
foreach($dc in $dcs)
{
$PSinstance = [powershell]::Create().AddScript($Code).AddArgument($username).AddArgument($dc)
$PSinstance.RunspacePool = $RunspacePool
$PSinstance.BeginInvoke()
}
So I just need to wait for each job to finish and then capture the results of each which is what I am not sure how to do
Edit: Also I had previously tried to do this with jobs but the code actually took longer than the normal scrip
$userName = Read-Host "Enter NTID: "
$time = 0
$dcs = Get-ADDomainController -Filter {Name -like "*"} | Select -expandproperty name
$scriptbox = {
Param($username,$dc)
Get-ADUser $username | Get-ADObject -Server $dc -Properties lastLogon | Select -Expandproperty lastLogon
}
foreach($dc in $dcs){start-Job -ScriptBlock $scriptbox -ArgumentList $username,$dc}
Get-Job | Wait-Job
Get-Job
$Data = ForEach ($Job in (Get-Job)) {
Receive-Job $Job
Remove-Job $Job
}
Foreach ($date in $Data){if($date -gt $time){$time = $date}}
$dt = [DateTime]::FromFileTime($time)
write-Host $username "last logged on at:" $dt