Powershell相当于bash&符(&),用于派生/运行后台进程

您所在的位置:网站首页 健康码三色含义图片 Powershell相当于bash&符(&),用于派生/运行后台进程

Powershell相当于bash&符(&),用于派生/运行后台进程

2024-07-17 16:31:50| 来源: 网络整理| 查看: 265

在bash中,"&"号可用于在后台运行命令,并在命令完成运行之前将交互式控件返回给用户。 在Powershell中有等效的方法吗?

在bash中的用法示例:

1 sleep 30 &

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

1Start-Process -NoNewWindow ping google.com

您还可以将此功能添加到您的个人资料中:

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

然后调用变为:

1bg ping google.com

在我看来,对于在后台运行流程的简单用例而言,Start-Job是一个过大的矫形:

Start-Job无权访问您现有的范围(因为它在单独的会话中运行)。您无法执行"开始工作{notepad $ myfile}" Start-Job不会保留当前目录(因为它在单独的会话中运行)。如果myfile.txt在当前目录中,则无法执行"开始作业{notepad myfile.txt}"。 输出不会自动显示。您需要使用作业的ID作为参数来运行Receive-Job。

注意:关于您的第一个示例," bg sleep 30"将不起作用,因为睡眠是Powershell Commandlet。仅当您实际分叉一个进程时,启动进程才起作用。

相关讨论 很高兴我找到了这个答案。我在寻找与Unix两次分叉机制相同的机制。在我看来,当PS shell退出时,以Start-Job开头的内容将被杀死。相反,在PS shell退出后,以Start-Process开头的内容似乎将继续运行。这是一个主要区别。 是的-如果您使用Start-Process启动脚本,它将在shell终止后继续存在,但是,如果您从控制台窗口启动脚本,则它将保持绑定到该窗口,并且关闭该窗口将终止该进程。 但是请注意,您不能使用Start-Process进行输出重定向,因此这将不起作用:Start-Process {ping -n 1000 example.com > ping__example.com.txt }。与Start-Job相同的东西可以正常工作(尽管您必须使用输出文件的完整路径)。 尝试执行此操作以运行节点Web服务器,并且在退出Powershell时该过程终止。有人知道为什么吗? @Jel不,但是Gusss评论谈到了这一点。 我希望可以使用脚本。等等,我有东西。 启动进程powershell -NoNewWindow -ArgumentList -file。 loop.ps1 我假设第一行意味着我不能将其用于cmdlet? 如果您还需要PID-例如一个可怜的人linux超时$x = Start-Process -Filepath"ping" -ArgumentList google.com -n 100 -NoNewWindow -PassThru; Start-Sleep -Seconds 5; try { Stop-Process -Id $x.Id -ErrorAction stop } catch {};这将ping 5秒钟,如果进程仍在运行,则将其杀死。如果需要提前终止,可以将"开始睡眠"更改为继续或中断的循环。

这是该问题的一些答案。

您在第1版中很难做到 版本2(现在在社区技术预览2中)确实具有此功能,称为作业(以前称为PSJob)。在此处或此处查找有关此内容的更多信息。 实际上,您可以在v1中用困难的方式做到这一点,可以随意使用,但我从来没有打扰过。 相关讨论 @Marcin-这个答案来自2008年。在Windows 7中,powershell 2.0是RTM,具有用于后台作业的" start-job" cmdlet。 不是在我的Windows 7上。 @marcin键入" get-command * job",您应该看到几个结果。检查这些帮助页面,如有任何新问题。 Start-Job会在托管Powershell进程终止时死亡,因此它不是可行的fork替换。 您需要将链接中的要点合并或总结为答案。

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

例如:

1Start-Job { C:\absolute\path\to\command.exe --afileparameter C:\absolute\path\to\file.txt } 相关讨论 因此,例如,如果我需要在命令行中运行Git Pull,则需要指定所有内容的完整路径...?那真烦人。 谢谢,很棒的提示,一直忙着不做的工作,这就是为什么。 @CMCDragonkai或只执行Start-Job {cd C: Path To repo; git pull}

1ps2> start-job {start-sleep 20}

我还没有弄清楚如何实时获取stdout,start-job要求您通过get-job来轮询stdout

更新:我不能开始工作轻松地做我想要的,基本上是bash&运算符。到目前为止,这是我最好的技巧

123456PS> 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 相关讨论 从PowerShell v3.0开始,您可以像这样实时获取stdout:Start-Job { Write-Output Hello world } | Receive-Job -Wait

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

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

求职 获取在当前会话中运行的Windows PowerShell后台作业 接收工作 获取当前会话中Windows PowerShell后台作业的结果 删除工作 删除Windows PowerShell后台作业 开始工作 启动Windows PowerShell后台作业 停止工作 停止Windows PowerShell后台作业 等待工作 禁止命令提示符,直到会话中运行的一个或所有Windows PowerShell后台作业完成

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

相关讨论 很好的答案,因为它涉及Powershell 3+。 job cmdlet与以前的答案有什么区别?

在PowerShell Core 6.0中,您可以在命令末尾编写&,这等效于在后台在当前工作目录中运行管道。

它与bash中的&不等效,它只是当前PowerShell作业功能的更好语法。它返回一个作业对象,因此您可以使用将用于作业的所有其他命令。例如Receive-Job:

1234567891011121314151617181920C:\utils> ping google.com & Id     Name            PSJobTypeName   State         HasMoreData     Location             Command --     ----            -------------   -----         -----------     --------             ------- 35     Job35           BackgroundJob   Running       True            localhost            Microsoft.PowerShell.M... C:\utils> Receive-Job 35 Pinging google.com [172.217.16.14] with 32 bytes of data: Reply from 172.217.16.14: bytes=32 time=11ms TTL=55 Reply from 172.217.16.14: bytes=32 time=11ms TTL=55 Reply from 172.217.16.14: bytes=32 time=10ms TTL=55 Reply from 172.217.16.14: bytes=32 time=10ms TTL=55 Ping statistics for 172.217.16.14:     Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds:     Minimum = 10ms, Maximum = 11ms, Average = 10ms C:\utils>

如果要在后台执行几条语句,可以将&调用运算符,{ }脚本块和此新的&后台运算符结合使用,如下所示:

1& { cd .\SomeDir\; .\SomeLongRunningOperation.bat; cd ..; } &

这是来自文档页面的更多信息:

从PowerShell Core 6.0的新增功能中:

Support backgrounding of pipelines with ampersand (&) (#3360)

Putting & at the end of a pipeline causes the pipeline to be run as a PowerShell job. When a pipeline is backgrounded, a job object is returned. Once the pipeline is running as a job, all of the standard *-Job cmdlets can be used to manage the job. Variables (ignoring process-specific variables) used in the pipeline are automatically copied to the job so Copy-Item $foo $bar & just works. The job is also run in the current directory instead of the user's home directory. For more information about PowerShell jobs, see about_Jobs.

来自about_operators /和号背景运算符&:

Ampersand background operator &

Runs the pipeline before it in a PowerShell job. The ampersand background operator acts similarly to the UNIX"ampersand operator" which famously runs the command before it as a background process. The ampersand background operator is built on top of PowerShell jobs so it shares a lot of functionality with Start-Job. The following command contains basic usage of the ampersand background operator.

1Get-Process -Name pwsh &

This is functionally equivalent to the following usage of Start-Job.

Start-Job -ScriptBlock {Get-Process -Name pwsh}

Since it's functionally equivalent to using Start-Job, the ampersand background operator returns a Job object just like Start-Job does. This means that you are able to use Receive-Job and Remove-Job just as you would if you had used Start-Job to start the job.

12$job = Get-Process -Name pwsh & Receive-Job $job

Output

123456789NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName ------    -----      -----     ------      --  -- -----------     0     0.00     221.16      25.90    6988 988 pwsh     0     0.00     140.12      29.87   14845 845 pwsh     0     0.00      85.51       0.91   19639 988 pwsh $job = Get-Process -Name pwsh & Remove-Job $job

For more information on PowerShell jobs, see about_Jobs.

相关讨论 感谢您所做的出色总结,其中100页的MS页面无法完成。 知道如何处理控制台作业吗?我用Receive-Job 3尝试了上述方法,但是什么也没发生。 @ not2qubit我不确定"控制台作业"是什么意思。您要在后台运行什么命令? 我当时使用的是一个启动Windows控制台的应用程序,但我无法获得任何输出,希望将其与nix world fg类似地用于将工作引入* foreground。 @ not2qubit不幸的是,在powershell中似乎没有与Unix fg类似的东西:(我记得在寻找它,但是找不到任何东西

你可以做这样的事情。

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

如果要等待:

1$a | wait-process

奖金osx或linux版本:

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

我有示例pinger脚本。 args作为数组传递:

1$1 = start -n powershell pinger,comp001 -pa 相关讨论 start 将派生该过程并将控制权返回给调用者。更多信息在这里 @Aethalides start实际上是powershell中启动过程的别名。

tl; dr

1Start-Process powershell { sleep 30 }

我已经在PowerShell v1.0中成功使用了此处描述的解决方案http://jtruher.spaces.live.com/blog/cns!7143DA6E51A2628D!130.entry。在PowerShell v2.0中肯定会更容易。



【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


    图片新闻

    实验室药品柜的特性有哪些
    实验室药品柜是实验室家具的重要组成部分之一,主要
    小学科学实验中有哪些教学
    计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
    实验室各种仪器原理动图讲
    1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
    高中化学常见仪器及实验装
    1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
    微生物操作主要设备和器具
    今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
    浅谈通风柜使用基本常识
     众所周知,通风柜功能中最主要的就是排气功能。在

    专题文章

      CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭