How to do something if work is over

I am trying to implement a GUI for my PowerShell script to simplify a specific process for other users. I have the following PowerShell script:

if ($checkBox1.Checked)    { 
    Try{
    Start-Job { & K:\sample\adp.cmd }
    $listBox1.Items.Add("ADP-Job started...")
    }catch [System.Exception]{
    $listBox1.Items.Add("ADP --> .cmd File not found!")}
    }

    if ($checkBox2.Checked)    { 
    Try{ 
    Start-Job { & K:\sample\kdp.cmd }
    $listBox1.Items.Add("KDP-Job started...")
    }catch [System.Exception]{
    $listBox1.Items.Add("KDP --> .cmd File not found!")}
    }

Is there a way to constantly check all tasks in progress and do something for each completed task? For example, to print something like this on my list:ADP-Files have been uploaded

Since each Job takes about 5 minutes - 4 hours, I thought of a Loop that checks every 5 minutes if Job is complete, but I cannot figure out how to distinguish each job to do something specific.

+4
source share
2 answers

You can specify the name of the task using the parameter -Name:

Start-Job { Write-Host "hello"} -Name "HelloWriter"

Get-Job:

Get-Job -Name HelloWriter

:

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
3      HelloWriter     BackgroundJob   Completed     True            localhost             Write-Host "hello"

Start-Job :

$worldJob = Start-Job { Write-Host "world"}

, $woldJob :

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
7      Job7            BackgroundJob   Completed     True            localhost             Write-Host "world" 

. Register-ObjectEvent, , :

$job = Start-Job { Sleep 3; } -Name "HelloJob"

$jobEvent = Register-ObjectEvent $job StateChanged -Action {
    Write-Host ('Job #{0} ({1}) complete.' -f $sender.Id, $sender.Name)
    $jobEvent | Unregister-Event
}
+6

:

$Var = Start-Job { & K:\sample\kdp.cmd }

$Var.State

Start-Job { & K:\sample\kdp.cmd } -Name MyJob

Get-Job MyJob
+2

Source: https://habr.com/ru/post/1651014/


All Articles