Question
How can we ask an asynchronous PowerShell job to gracefully stop on its own?
Short Answer
We can use a marker file pattern for that effect:
# this is the path to the marker file
$JobStopMarkerFile = "C:\Temp\JobStopMarker.txt";
# ensure the marker file does not exist
if (Test-Path -LiteralPath $JobStopMarkerFile)
{
Remove-Item $JobStopMarkerFile
}
# this contains the script to run async
$JobScript = {
param
(
[Parameter(Mandatory = $true)]
$JobStopMarkerFile
)
# this flag will be set when the job is done
$IsJobDone = $false
# this condition checks whether
# 1) the job is done
# 2) the job has been asked to stop
while (-not $IsJobDone)
{
# some recurring task would run here instead
Start-Sleep -Seconds 5
# uncomment and set this whenever the job finishes on its own
# $IsJobDone = $true
# check if the marker file exists
if (Test-Path -LiteralPath $JobStopMarkerFile)
{
# signal the job as completed
$IsJobDone = $true;
# cleanup the file too
Remove-Item -LiteralPath $JobStopMarkerFile
}
}
}
# start the job now
$Job = Start-Job -ScriptBlock $JobScript -ArgumentList $JobStopMarkerFile
# do some other stuff here
Start-Sleep 1
# ask the job to stop
# we do this by *creating* an empty marker file
# the job itself will remove this file
$null > $JobStopMarkerFile
# wait for the job to finish
Wait-Job $Job
There is quite some code here, isn’t there? So how does it work?
Long Answer
If we just want to stop a job, minus the gracefully bit, we can simply use the Stop-job Cmdlet:
Continue reading “How To Gracefully Stop An Asynchronous Job In PowerShell” →
Like this:
Like Loading...