In the code blocks below, I'm trying to run Get-MyCmdlet in 3 separate threads, each of which opens a google page if the Get-MyCmdlet did not give anything.
The Get-MyCmdlet is fairly simple, the only thing it does is WriteObject("hello world"); (defined in the c# code).
However the script always opens up a google page, unless I change the Get-MyCmdlet to Get-Host(which is a system default cmdlet).
Is it because the custom cmdlets are not supporting multi-threading? Any help will be greatly appreciated!
The cmdlet:
[Cmdlet(VerbsCommon.Get, "MyCmdlet ")]
public class GetMyCmdlet : Cmdlet
{
protected override void ProcessRecord()
{
WriteObject("hello world");
}
}
the script:
$ScriptBlock = {
$result = Get-MyCmdlet
if (!$result) {[System.Diagnostics.Process]::Start("http://www.google.com")}
$name = ($result | get-member)[-1].name
$result = $result.$name
return $result
}
....
$threads = 3
for ($i = 0; $i -lt $threads) {
$running = @($jobs | Where-Object {$_.State -match 'Running'})
Write-Host $running.length
if ($running.length -lt $threads) {
$jobs += Start-job -ScriptBlock $ScriptBlock
$i = $i + 1
} else {
get-job | receive-job
$finished = @($jobs | Where-Object ($_.State -match 'Completed'))
if ($finished) {
$finished.getType()
foreach($job in $finished) {
Receive-Job -keep $job | Out-File "Output$.txt"
$i = $i + 1
$finished.Remove($job)
Remove-Job -job $job
}
}
}
}