Sec99
Sec99

Reputation: 3

If a job has status completed execude code in powershell

After about half a day of googling without any luck I've decided to post my question here.

So I want to check if a job has status completed.

Here is my code so far:

 Start-job -name Copy -Scriptblock {Copy-Item -force -recurse -path
 "C:\Test.temp" -destination "D:\"}

 $x = 170 $length = $x / 100 While($x -gt 0) {

 $min ) [int](([string]($x/60)).Split('.')[0]) $Text = " " + $min + "
 mintues " + ($x % 60) + " seconds left" Write-progress "Copying file,
 estimated time remaning" -status $text -percentComplete ($x/$length)
 Start-sleep -s 1 $x--

 if (Get-job -name Copy -status "Completed") { Break } }

So as you can see I first start a job, then I run a loop with a countdown progress bar. This is just to give the user some kind of feedback that things are still moving. Note that the "Get-job -status "completed" doesn't work since it's not a parameter of Get-job.

The problem now is that I can't get the "if get job has completed, break the loop" since the copying job might be done before the progress bar.

Does anyone know a good solution to this? Thanks in advance!

Upvotes: 0

Views: 1791

Answers (2)

tukan
tukan

Reputation: 17347

I think you could get the condition to work like this:

if ( Get-job -State Completed | Where-Object {$_.Name.Contains("Copy"){ Break }

Your -status does not exist in the get-job

Upvotes: 0

Drew
Drew

Reputation: 4020

Using ForEach is probably your best bet for breaking the loop cleanly once done.

This shows a progress bar but no timer, more so just a per file progress so it will tell you what it is up to and whats taking a while.

$srcPath = 'C:\Test.temp'
$destPath = 'D:\'
$files = Get-ChildItem -Path $srcPath -Recurse
$count = $files.count
$i=0

ForEach ($file in $files){
    $i++
    Write-Progress -activity "Copying from $srcPath to $destPath" -status "$file ($i of $count)" -percentcomplete (($i/$count)*100)
    if($file.psiscontainer){
        $sourcefilecontainer = $file.parent
    } else {
        $sourcefilecontainer = $file.directory
    }
    $relativepath = $sourcefilecontainer.fullname.SubString($srcPath.length)
    Copy-Item $file.fullname ($destPath + $relativepath) -force
}

Upvotes: 1

Related Questions