用于派生/运行后台进程的 bash 与符号 (&) 的 Powershell 等效项 [英] Powershell equivalent of bash ampersand (&) for forking/running background processes

查看:11
本文介绍了用于派生/运行后台进程的 bash 与符号 (&) 的 Powershell 等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 bash 中,与号 (&) 可用于在后台运行命令并在命令完成运行之前将交互控制返回给用户.是否有在 Powershell 中执行此操作的等效方法?

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 equivalent method of doing this in Powershell?

bash 中的用法示例:

Example of usage in bash:

 sleep 30 &

推荐答案

只要命令是可执行文件或具有关联可执行文件的文件,就使用 Start-Process(可从 v2 获得):

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}

然后调用变成:

bg ping google.com

在我看来,Start-Job 对于在后台运行进程的简单用例来说是一种矫枉过正:

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

  1. Start-Job 无权访问您现有的范围(因为它在单独的会话中运行).你不能做开始工作 {notepad $myfile}"
  2. Start-Job 不保留当前目录(因为它在单独的会话中运行).您不能在 myfile.txt 位于当前目录中的位置执行Start-Job {notepad myfile.txt}".
  3. 输出不会自动显示.您需要使用作业的 ID 作为参数运行 Receive-Job.

注意:关于您最初的示例,bg sleep 30"不起作用,因为 sleep 是 Powershell commandlet.Start-Process 仅在您实际 fork 进程时才起作用.

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.

这篇关于用于派生/运行后台进程的 bash 与符号 (&) 的 Powershell 等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆