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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With