Link to home
Create AccountLog in
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}

}
Avatar of Jeremy Weisinger
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

Avatar of 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.
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.
ASKER CERTIFIED SOLUTION
Avatar of Jeremy Weisinger
Jeremy Weisinger

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Viable solution.