Syphirint Syphirint - 4 months ago 18
PowerShell Question

Job to check job state

I'm trying to check what it's the state of the previously started jobs without blocking the session I am in.
So I tried something like this:

Start-Job -ScriptBlock {
while($true){
$i++
Start-Sleep -Seconds 1
}
}

Start-Job -ScriptBlock {
switch ((Get-Job)[0].State){
"Stopped" {
write-host "Stopped"
}
"Running"{
write-host "Running"
}
default {
write-host "Something else"
}
}
}

Get-Job | Receive-Job


But it throws an error saying that I can not index into a
null
array, even when I have several jobs running.

Is there a way for starting a job that allow me to check the other jobs state?

Answer

    Since jobs "live" in different "spaces" (poor technicality, sorry for that), they can't see each other. So, the solution that I found is to run a ScriptBlock whenever a timer throws an event. This way, the other jobs continue undisturbed.

Start-Job -ScriptBlock {
    while($true){
        $i++
        Start-Sleep -Seconds 1
    }
}

$timer = New-Object System.Timers.Timer
$timer.AutoReset = $true #repeat?
$timer.Interval = 500 #ms

Register-ObjectEvent -InputObject $timer -EventName Elapsed -Action {   
    $job_state = (Get-Job)[0].State
    switch ($job_state){
        "Stopped" {
            write-host "Stopped"
        }
        "Running"{
            write-host "Running"
        }
        default {
            write-host "Something else"
        }
    }
}

$timer.Start()

This way if the first job is in a state that isn't supposed to be, i can be notified.