Start-Job hangs Powershell on Windows 2016
Posted: Wed Oct 02, 2019 8:45 am
Not sure if anyone else has seen this, but there's what must be a bug that occasionally causes the parent thread to hang when trying to run Start-Job and if you're starting a bunch of jobs on a loop you'll probably hit it for sure. If you're hitting this and are looking for a workaround, I have one but it's a bit complicated.
Create a new sub-thread and launch the job from there. Here's some sample code. There are probably several different ways to detect when the start-job process fails.
From there you can deal with the threads in taskList. Most of the code to deal with threads was pulled from the start-parallel module. The rest I threw together.
Anyone else seeing this with Windows 2016?
Create a new sub-thread and launch the job from there. Here's some sample code. There are probably several different ways to detect when the start-job process fails.
Code: Select all
$ChildScriptBlock = {
$Parameters = $args[0]
$log = '<your path to log files>\' + $Parameters["jobName"] + '.txt'
"Child Script: Got " + $Parameters["P1"] + " and " + $Parameters["P2"] + " With fallback of " + $Parameters["Fallback"]>> $log
#$Parameters["P1"] >> $log
}
$ParentScriptBlock = {
$ParentParameters = $args[1]
$ChildScriptBlock = $ParentParameters["ChildScriptBlock"]
$log = '<your path to log files>\' + $ParentParameters["jobName"] + '.txt'
#"Got " + $ParentParameters["P1"] + " and " + $ParentParameters["P2"] >> $log
$ChildParameters = @{
Fallback = "fallback";
}
foreach ($key in $ParentParameters.Keys)
{
if ($key -ne "ChildScriptBlock")
{
#"Adding key $key to ChildParameters" >> $log
$ChildParameters[$key] = $ParentParameters[$key]
}
}
$job = Start-Job -Name $ParentParameters["jobName"] -ScriptBlock $ChildScriptBlock -ArgumentList $ChildParameters
}
$ParentParameters = @{
P1 = "Parameter 1";
P2 = "Parameter 2";
ChildScriptBlock = $ChildScriptBlock;
}
$runspacePool = [runspacefactory]::CreateRunspacePool()
$runspacePool.Open()
$taskList = @()
for ($jobnumber = 1; $jobnumber -lt 200; $jobnumber++)
{
$ParentParameters["jobName"] = "job_$jobnumber"
$newThread = [powershell]::Create().AddScript($ParentScriptBlock).AddParameter('ParentParameters', $ParentParameters)
$newThread.RunspacePool = $runspacePool
$handle = $newThread.BeginInvoke()
$taskList += New-Object -TypeName psobject -Property @{ "Handle" = $handle; "Thread" = $newThread; }
Start-Sleep 1
}
$taskList | Where-Object { $_.Handle.IsCompleted } | ForEach-Object {
$_.Thread.EndInvoke($_.Handle)
$_.Thread.Dispose()
$_.Thread = $_.Handle = $Null
}
Anyone else seeing this with Windows 2016?