I created a powershell job, I want to limit it's running time to 10 seconds. so I used the Wait-Job command, and if it times out I execute a Stop-Job command. The problem is that the Stop-Job command takes about 2 minutes. How can I fix it and stop the job immediately?
While($hasTimeFromNTP -eq $false)
{
Write-Host "Start get time from NTP" -ForegroundColor Yellow
Start-Job -Name GetNTPTime -ScriptBlock $getTimeFromNtp | Out-Null
$result = Wait-Job GetNTPTime -Timeout 10
if($result -ne $null)
{
$NTPTime = Receive-Job GetNTPTime
$hasTimeFromNTP = $true
}
else
{
Write-Host "GetTimeFromNTP timed out"
Stop-Job GetNTPTime
Remove-Job GetNTPTime -Force
}
}
Thanks
I don't see a -Force
parameter on Stop-Job. One option would be to have the Job return the PowerShell process id it is running in $pid
as the initial output. You could use that pid to Stop-Process on the Powershell.exe spun up for that background job. That's harsh but if you don't want to wait for 2 minutes, I'm not seeing other ways to force the job to stop quicker.