I'm having trouble getting background threads to work in Powershell. I'd like to use runspaces where I can plug a script into it and get updates when there is one and allow my main thread to do with that data what it needs to. I'm not sure why doesn't this code return the proper values? All of the servers I tested against return true when not used in a runspace, but the return value here is 0.
I'm not interested in using powershell jobs.
$servers = @("x1","x2","x3");
$results = New-Object Collections.Generic.List[String];
$input = New-Object 'System.Management.Automation.PSDataCollection[psobject]'
$output = New-Object 'System.Management.Automation.PSDataCollection[psobject]'
$results.Clear();
foreach ($server in $servers)
{
Write-Host $server;
$powerShell = [Management.Automation.PowerShell]::Create();
[Void]$PowerShell.AddScript({
$result = Test-Connection $server -Count 1 -Quiet;
return ($server - $result)
})
$handle = $powerShell.BeginInvoke($input,$output);
$results.Add($output);
}
$results;
or
$results = New-Object Collections.Generic.List[String];
$input = New-Object 'System.Management.Automation.PSDataCollection[psobject]'
$output = New-Object 'System.Management.Automation.PSDataCollection[psobject]'
$results.Clear();
foreach ($server in $servers)
{
Write-Host $server;
$powerShell = [Management.Automation.PowerShell]::Create();
[Void]$PowerShell.AddScript({
param ($server)
$result = Test-Connection $server -Count 1 -Quiet;
return ($server - $result)
})
$handle = $powerShell.BeginInvoke($server,$output);
#$handle = $powerShell.BeginInvoke($input,$output);
$results.Add($output);
}
$results;