백그라운드 프로세스 포크 / 실행을위한 bash 앰퍼샌드 (&)와 동등한 Powershell
bash에서는 앰퍼샌드 (&)를 사용하여 백그라운드에서 명령을 실행하고 명령 실행이 완료되기 전에 대화식 제어를 사용자에게 반환 할 수 있습니다. Powershell에서 이와 동등한 방법이 있습니까?
bash에서의 사용 예 :
sleep 30 &
이 질문에 대한 몇 가지 답변입니다.
- 버전 1에서는 쉽게 할 수 없습니다
- 버전 2 (현재 커뮤니티 기술 미리보기 2에서)에는이 기능이 있으며이를 작업 (이전의 PSJob)이라고합니다. 여기 또는 여기 에서 이에 대해 자세히 알아보십시오 .
- 실제로 v1에서는 어려운 방법으로 할 수 있습니다. 부담없이 사용하지만 결코 신경 쓰지 않았습니다.
명령이 실행 파일이거나 관련 실행 파일이있는 파일 인 경우 Start-Process (v2에서 사용 가능)를 사용 하십시오 .
Start-Process -NoNewWindow ping google.com
이것을 프로파일에 함수로 추가 할 수도 있습니다.
function bg() {Start-Process -NoNewWindow @args}
그러면 호출은 다음과 같습니다.
bg ping google.com
제 생각에는 Start-Job은 백그라운드에서 프로세스를 실행하는 간단한 사용 사례에 대한 과도한 것입니다.
- Start-Job은 별도의 세션에서 실행되기 때문에 기존 범위에 액세스 할 수 없습니다. "Start-Job {notepad $ myfile}"을 수행 할 수 없습니다
- Start-Job은 현재 디렉토리를 보존하지 않습니다 (별도의 세션에서 실행되기 때문에). myfile.txt가 현재 디렉토리에있는 "Start-Job {notepad myfile.txt}"를 수행 할 수 없습니다.
- 출력이 자동으로 표시되지 않습니다. 작업 ID를 매개 변수로 Receive-Job을 실행해야합니다.
참고 : 초기 예제와 관련하여 절전 모드는 Powershell 커맨드 렛이므로 "bg sleep 30"이 작동하지 않습니다. 시작 프로세스는 실제로 프로세스를 분기 할 때만 작동합니다.
전달 된 스크립트 블록 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은 stdout을 get-job로 폴링해야합니다.
업데이트 : 기본적으로 bash & operator 인 원하는 작업을 쉽게 수행 할 수 없습니다. 여기까지 내 최고의 해킹이 있습니다.
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
PowerShell 작업 cmdlet을 사용하여 목표를 달성 할 수 있습니다.
PowerShell에는 6 가지 작업 관련 cmdlet이 있습니다.
- Get-Job
- 현재 세션에서 실행중인 Windows PowerShell 백그라운드 작업을 가져옵니다.
- 직업을 받기
- 현재 세션에서 Windows PowerShell 백그라운드 작업의 결과를 가져옵니다.
- 제거 작업
- Windows PowerShell 백그라운드 작업을 삭제합니다.
- 작업 시작
- Windows PowerShell 백그라운드 작업을 시작합니다.
- 스톱 잡
- Windows PowerShell 백그라운드 작업을 중지합니다.
- 잠깐만
- 세션에서 실행중인 하나 또는 모든 Windows PowerShell 백그라운드 작업이 완료 될 때까지 명령 프롬프트를 표시하지 않습니다.
흥미가 있다면 PowerShell에서 백그라운드 작업을 만드는 방법 샘플을 다운로드 할 수 있습니다.
PowerShell Core 6.0부터는 &
명령 끝 에서 쓸 수 있으며 현재 작업 디렉토리에서 백그라운드로 파이프 라인을 실행하는 것과 같습니다 .
&
bash 와 동일하지 않으며 현재 PowerShell 작업 기능에 대한 더 좋은 구문 일뿐 입니다. 작업 오브젝트를 리턴하므로 작업에 사용할 다른 모든 명령을 사용할 수 있습니다. 예를 들면 Receive-Job
다음과 같습니다.
C:\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>
백그라운드에서 몇 개의 명령문을 실행하려면 &
call 연산자 , { }
스크립트 블록 및이 새로운 &
background 연산자를 다음 과 같이 결합 할 수 있습니다.
& { cd .\SomeDir\; .\SomeLongRunningOperation.bat; cd ..; } &
다음은 설명서 페이지의 추가 정보입니다.
에서 PowerShell을 코어 6.0의 새로운 기능 :
앰퍼샌드 (&)를 사용하여 파이프 라인의 백그라운드 지원 (# 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 soCopy-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.
from about_operators / Ampersand background operator &:
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.Get-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 aJob
object just likeStart-Job does
. This means that you are able to useReceive-Job
andRemove-Job
just as you would if you had usedStart-Job
to start the job.$job = Get-Process -Name pwsh & Receive-Job $job
Output
NPM(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.
You can do something like this.
$a = start-process -NoNewWindow powershell {timeout 10; 'done'} -PassThru
done
And if you want to wait for it:
$a | wait-process
Bonus osx or linux version:
$a = start-process pwsh '-c',{start-sleep 5; 'done'} -PassThru
Example pinger script I have. The args are passed as an array:
$1 = start -n powershell pinger,comp001 -pa
I've used the solution described here http://jtruher.spaces.live.com/blog/cns!7143DA6E51A2628D!130.entry successfully in PowerShell v1.0. It definitely will be easier in PowerShell v2.0.
tl;dr
Start-Process powershell { sleep 30 }
'development' 카테고리의 다른 글
TypeError : 해시 할 수없는 유형 : 'dict' (0) | 2020.06.23 |
---|---|
루비를위한 최고의 / 쉬운 GUI 라이브러리는 무엇입니까? (0) | 2020.06.23 |
"동결 된 dict"은 무엇입니까? (0) | 2020.06.23 |
람다와 함께 JDK8을 사용하여 압축 스트림 (java.util.stream.Streams.zip) (0) | 2020.06.23 |
ASP.NET MVC 및 IIS7에서 원시 HTTP 요청 / 응답 로깅 (0) | 2020.06.23 |