Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

how do I do a background task in powershell?

$ ant >/dev/null &        #cygwin

the closest i can get to this in powershell is

ps2> start-job {ant |out-null; `a}   #powershell

but then i don't get output in real-time, nor do i get the beep, i have to poll for it with receive-job and get the beep when stdout gets polled.

share|improve this question
add comment

1 Answer

Hopefully you are on Powershell Version 2. If you are then this is how to background process a job:

Start-Job {Get-Process}

That will run the job in the background. If you want to interact with the job, then just assign it to a variable:

$foo = Start-Job {Get-Process}

Now of course the trickiness comes with knowing when the job is done. I realize that is the purpose of the bell that you put in your original example. Unfortunately Powershell holds the pipe until you ask for the results from the job. To get the results from the job use the Receive-Job cmdlet:

Receive-Job $foo

I am interested in a way to alert when a background job has completed as well so I will keep looking for a solution to that.

Oh and for more info:

Get-Help about_jobs

Ok, so here is how to get a beep on completion. First, read this Get Notification When A Background Job Is Done (that is a great resource site by the way). I took the info there and I added this function to my profile:

function Register-JobWait{
param(
        $Job
     )
Register-ObjectEvent $job StateChanged -Action {
[Console]::Beep(1000,500)
$eventSubscriber | Unregister-Event
$eventSubscriber.Action | Remove-Job
} | Out-Null

}

I also added an alias in my profile:

set-alias rjw Register-JobWait

so now if I want to background process something I do this:

$foo = Start-Job {1..10 | Get-Process}
rjw $foo

I wait for the beep then:

Receive-Job $foo
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.