Self terminating jobs in PowerShell

Tagged: 

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 1 year, 10 months ago.

  • Author
    Posts
  • #22119

    Is it possible to create a PowerShell job using start-job which will terminate itself once completed?
    For example the script block would check some conditions and write the result to a log file, after which it should terminate itself (the job within which it is running).
    In other words I would start many short jobs from the main script block, but I don't need to receive anything from them and I would like to avoid keeping track of them and having to use remove-job to terminate them all.

  • #22120
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Sort of. You can't do that from inside the job itself (because it's usually running in a different process), but you can register an event that fires when the job finishes and cleans up after itself. Here's some demo code of that:

    $job = Start-Job -ScriptBlock { Start-Sleep -Seconds 10 }
    $null = Register-ObjectEvent $job -EventName StateChanged -Action {
        if ($eventArgs.JobStateInfo.State -eq [System.Management.Automation.JobState]::Completed)
        {
            Write-Host -ForegroundColor Green 'Event triggering'
    
            # This command removes the original job
            $sender | Remove-Job -Force
    
            # These commands remove the event registration
            $eventSubscriber | Unregister-Event -Force
            $eventSubscriber.Action | Remove-Job -Force
        }
    }
    
    Write-Verbose -Verbose 'Before:'
    
    Get-Job | Out-Host
    
  • #22122

    Thank for the quick reply! One question:
    what is the $sender variable?

    • #22123
      Profile photo of Dave Wyatt
      Dave Wyatt
      Moderator

      $sender, $eventArgs and $eventSubscriber are all automatic variables set inside the Action block of an event subscription. There are a few others as well, in the about_Automatic_Variables help file.

You must be logged in to reply to this topic.