Clean up before exiting script

I have a script that does a few things before starting a job and then executing:

get-content $OutFile -Tail 100 -Wait

Resulting in a background job producing an output to a file that is tailed and displayed.
Pressing Ctrl-C will exit the script altogether. All this works fine.

But, I would want the script to kill the job before exiting, after canceling the get-content command.

Is this possible in any way?

Use cmdlet ‘Remove-Job’ to delete a background job. What have you tried so far?

I think he is referencing catching the CTRL/C action and then killing the job before the script cancels ???

Yes, that is right. Right now I have a remove-job at the beginning of the script, removing any old instances of the job. But I really would like the job to be removed before the script ends.

If you end the script with <Ctrl>+<C> there is no way for your script to do anything else because it does not run anymore. You would need to implement a loop inside your script checking for a cancel condition and clean up before ending itself.

try - finally, did the trick.

try
{

  write-host Starting job.
  start-job  ........
  get-content  ........ -Tail 100 -Wait

}

finally
{

  write-host "Removing job, please wait ...."
  remove-job ......... -Force 2>$null
	
}

When entering ctr-c to exit get-content the job will be removed before the script ends.
Just the way I want it. :slight_smile:

1 Like