在bash中,&号(&)可用于在后台运行命令,并在命令运行完成之前将交互控制返回给用户。在Powershell中是否有等效的方法来做到这一点?

在bash中的用法示例:

 sleep 30 &

当前回答

博士tl;

Start-Process powershell { sleep 30 }

其他回答

您可以使用PowerShell作业cmdlet来实现您的目标。

在PowerShell中有6个与作业相关的cmdlet可用。

得到工作 获取在当前会话中运行的Windows PowerShell后台作业 接受职业 获取当前会话中Windows PowerShell后台作业的结果 Remove-Job 删除Windows PowerShell后台作业 启动作业 启动Windows PowerShell后台作业 Stop-Job 停止Windows PowerShell后台作业 Wait-Job 抑制命令提示符,直到会话中运行的一个或所有Windows PowerShell后台作业完成

如果感兴趣,可以下载如何在PowerShell中创建后台作业的示例

你可以这样做。

$a = start-process -NoNewWindow powershell {timeout 10; 'done'} -PassThru

如果你想等的话:

$a | wait-process

额外的osx或linux版本:

$a = start-process pwsh '-c',{start-sleep 5; 'done'} -PassThru 

示例ping脚本我有。参数作为数组传递:

$1 = start -n powershell pinger,comp001 -pa

传递给Start-Job的脚本块似乎没有在与Start-Job命令相同的当前目录下执行,因此如果需要,请确保指定完全限定的路径。

例如:

Start-Job { C:\absolute\path\to\command.exe --afileparameter C:\absolute\path\to\file.txt }
ps2> start-job {start-sleep 20}

我还没有弄清楚如何实时获得stdout, start-job要求你用get-job轮询stdout

更新:我不能开始工作轻松地做我想要的基本上是bash &操作符。这是我目前为止最好的一招

PS> notepad $profile #edit init script -- added these lines
function beep { write-host `a }
function ajp { start powershell {ant java-platform|out-null;beep} } #new window, stderr only, beep when done
function acjp { start powershell {ant clean java-platform|out-null;beep} }
PS> . $profile #re-load profile script
PS> ajp

博士tl;

Start-Process powershell { sleep 30 }