Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Foreground a Backgrounded Job invoked by Start-Job in Powershell for Windows

In Bash, it is possible to start a job in the background by putting an & at the end of the command. It is also possible to bring that job to the foreground by using the fg command, with appropriate job id if need be.

In Powershell, I understand the & equivalent is the Start-Job command. However, I am unable to find any information on methods to do the fg equivalent. Is there anyway to do that? Note that I am not asking about getting output. Rather, my question is as follows.

Does there exist a way to bring a running job to the foreground, taking control of the Powershell Window?

The main reason that such feature is needed is so that I can send keys/strings to the running job.

Using Windows 8.1 Pro.

like image 710
nehcsivart Avatar asked Aug 12 '15 11:08

nehcsivart


2 Answers

I've been burning the midnight oil and banging my head up against Google search after Google search. It turns out this is pretty easy using invoke-item.

Here is how I'm using it:

invoke-item .\form.ps1
timeout /t 90
wmic Path win32_process Where "CommandLine Like '%form.ps1%'" Call Terminate

This will call my script form.ps1 (a Windows form that I created) from within PowerShell. The Parent will continue to execute while form.ps1 is running.

I'm using

wmic Path win32_process Where "CommandLine Like '%form.ps1%'" Call Terminate

to kill the form by its command line name.

like image 93
Julian Avatar answered Oct 13 '22 03:10

Julian


It looks like you can do this with the -Wait switch of the Receive-Job command, e.g. Receive-Job -Wait -Id 3 (where 3 is the Id returned by Start-Job)

Here's an example of how I tested this (in PowerShell 5, with the output included):

> Start-Job -ScriptBlock {Read-Host -Prompt "Enter Something"; Read-Host -Prompt "Enter Something Else"}

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
1      Job1            BackgroundJob   Running       True            localhost            Read-Host -Prompt "Ent...

> Receive-Job -Wait -Id 1
Enter Something: something!
something!
Enter Something Else: something else!
something else!

So after issuing the Receive-Job -Wait command, the job went to the foreground and I was able to enter something! and something else! in response to the two prompts from the script block I passed to Start-Job.

like image 29
ornsio Avatar answered Oct 13 '22 03:10

ornsio