craig
craig

Reputation: 26262

PowerShell console timer

I am attempting to create a simple console timer display.

...

$rpt = $null
write-status "Opening report", $rpt

# long-running
$rpt = rpt-open -path "C:\Documents and Settings\foobar\Desktop\Calendar.rpt"

...

function write-status ($msg, $obj) {

    write-host "$msg" -nonewline

    do {
        sleep -seconds 1
        write-host "." -nonewline
        [System.Windows.Forms.Application]::DoEvents() 
    } while ($obj -eq $null)

    write-host

}

The example generates 'Opening report ....', but the loop never exits.

I should probably use a call-back or delegate, but I'm not sure of the pattern in this situation.

What am I missing?

Upvotes: 0

Views: 750

Answers (3)

alroc
alroc

Reputation: 28174

You should be using Write-Progress to inform the user of the run status of your process and update it as events warrant.

Upvotes: 2

E.V.I.L.
E.V.I.L.

Reputation: 2166

If you want to do some "parallel" computing with powershell use jobs.

$job = Start-Job -ScriptBlock {Open-File $file} -ArgumentList $file
while($job.status -eq 'Running'){
    Write-Host '.' -NoNewLine
}

Here is what I think about Write-Host.

Upvotes: 1

Frode F.
Frode F.

Reputation: 54881

The script runs in sequence. When you input a $null object, the while condition will always be true. The function will continue forever until something breaks it (which never happends in your script.

First then will it be done with the function and continue with your next lines:

# long-running
$rpt = rpt-open -path "C:\Documents and Settings\foobar\Desktop\Calendar.rpt"

Summary: Your while loop works like while($true) atm = bad design

Upvotes: 0

Related Questions