Powershell equivalent of bash ampersand (&) for forking/running background processes

后端 未结 8 1378
北海茫月
北海茫月 2020-11-28 20:33

In bash the ampersand (&) can be used to run a command in the background and return interactive control to the user before the command has finished running. Is there an

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 21:22

    As long as the command is an executable or a file that has an associated executable, use Start-Process (available from v2):

    Start-Process -NoNewWindow ping google.com
    

    You can also add this as a function in your profile:

    function bg() {Start-Process -NoNewWindow @args}
    

    and then the invocation becomes:

    bg ping google.com
    

    In my opinion, Start-Job is an overkill for the simple use case of running a process in the background:

    1. Start-Job does not have access to your existing scope (because it runs in a separate session). You cannot do "Start-Job {notepad $myfile}"
    2. Start-Job does not preserve the current directory (because it runs in a separate session). You cannot do "Start-Job {notepad myfile.txt}" where myfile.txt is in the current directory.
    3. The output is not displayed automatically. You need to run Receive-Job with the ID of the job as parameter.

    NOTE: Regarding your initial example, "bg sleep 30" would not work because sleep is a Powershell commandlet. Start-Process only works when you actually fork a process.

提交回复
热议问题