Avatar of janhoedt
janhoedt
 asked on

PS: function to schedule a script as job, popup once finished + remove job?

Hi,

I have a  PS function which schedules a script as a job by path which works fine.
However, I'd like it to popup with a message once done and remove the job.
Please advise.

This is the function so far:

  function Submit-PSSCriptJob
{
  [Cmdletbinding()]
  Param (
    [Parameter()]
    [String]$Path
  )
 

    Start-Job -Name PSCriptJob -ScriptBlock {powershell.exe -file $using:Path}

}
Powershell

Avatar of undefined
Last Comment
Jeremy Weisinger

8/22/2022 - Mon
Jeremy Weisinger

You could do something like this:

  function Submit-PSSCriptJob
{
  [Cmdletbinding()]
  Param (
    [Parameter()]
    [String]$Path
  )
  

    Start-Job -Name PSCriptJob -ScriptBlock {powershell.exe -file $using:Path} | Wait-Job
    "Job Complete"
    Get-Job PSCriptjob | Remove-Job

}

Open in new window

janhoedt

ASKER
If you wait for the job, the function is useless.
The main reason for this function is to not occupy the powershell console while a script is running.
janhoedt

ASKER
Googled a bit and came around with this:

 function Submit-PSSCriptJob
{
  [Cmdletbinding()]
  Param (
    [Parameter()]
    [String]$Path
  )
 

  $Job = Start-Job -Name PSCriptJob -ScriptBlock {powershell.exe -file $using:Path}
   
  $jobEvent = Register-ObjectEvent $job StateChanged -Action {
    Write-Host ('Job #{0} ({1}) complete.' -f $sender.Id, $sender.Name)
    $jobEvent | Unregister-Event


  }
   
}

Not sure what the jobevent is doing.
Result is this: Job #27 (PSCriptJob) complete, but then PS ISE freezes.
J.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
ASKER CERTIFIED SOLUTION
Jeremy Weisinger

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Jeremy Weisinger

Viable solution.