locked
let background job write to screen RRS feed

  • Question

  • Is there a way to write a script like this, run it in the background, but still allow it to write to the terminal?

    while (1) { echo hi; sleep 1 }    


    • Edited by JS2010 Saturday, September 16, 2017 6:35 PM
    Saturday, September 16, 2017 6:34 PM

All replies

  • You just did.  That line will write to the console -- we don't call it a terminal -- even if the console is running in the "background".


    \_(ツ)_/

    Saturday, September 16, 2017 7:25 PM
  • Yeah but I want it to run in the background like this:

    start-job { while (1) { echo hi; sleep 1 } } 



    • Edited by JS2010 Saturday, September 16, 2017 8:06 PM
    Saturday, September 16, 2017 8:06 PM
  • Do you have a question?  Are you asking how to get the output?

    help Receive-Job -Full

    A task running in a separate session cannot output to a different session.  You can possible use a runspace and a synchash to get an output.


    \_(ツ)_/


    • Edited by jrv Saturday, September 16, 2017 8:12 PM
    Saturday, September 16, 2017 8:10 PM
  • Yes, I want to do like this in unix.  I can still run other commands, but output will still come to the same screen by itself.

    while true; do echo hi; sleep 1; done &




    • Edited by JS2010 Saturday, September 16, 2017 8:41 PM
    Saturday, September 16, 2017 8:40 PM
  • There is no command in PowerShell to push a command into the background.  We can only use runspaces and synchashes.


    \_(ツ)_/

    Saturday, September 16, 2017 8:49 PM
  • Example of a runspace that writes to the console:

    #https://learn-powershell.net/2013/04/19/sharing-variables-and-live-objects-between-powershell-runspaces/
    
    $code = {
    	while(1){
    		$hash.host.Ui.WriteLine('Hello World!')
    		sleep 2
        }
    }
    
    $hash = [hashtable]::synchronized(@{ })
    $hash.Result = ''
    $hash.host = $host
    $runspace = [runspacefactory]::createrunspace()
    $runspace.open()
    
    $runspace.sessionstateproxy.setvariable('hash', $hash)
    $pipeline = $runspace.createpipeline($code)
    $pipeline.input.close()
    $pipeline.invokeasync()
    
    # to terminate runspace type "$runspace.Close();$runspace.Dispose()"
    


    \_(ツ)_/

    Saturday, September 16, 2017 10:32 PM
  • It can somewhat be done like this.

    $a = start-process -NoNewWindow powershell 'while (1) { echo hi; sleep 1 }' -PassThru
    hi
    hi
    hi
    stop-process $a

    • Edited by JS2010 Monday, October 7, 2019 7:58 PM
    Monday, October 7, 2019 7:53 PM