Reputation: 4606
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
}
}
}
}
Upvotes: 1
Views: 517
Reputation: 43595
No custom cmdlets are not the problem. My guess is the problem is that calling Get-MyCmdlet
fails with an error so $result is not set and thanks to your if the browser is started. If you would check the results of your jobs you would see an error message. You probably need to make sure the job initializes right so you can call your cmdlet. You could use the -InitializationScript
parameter of Start-Job
to import your module for the job. See here, here and here for more information.
Upvotes: 2