programing

PowerShell에서 각 명령이 종료될 때까지 기다렸다가 다음 명령을 시작하도록 지시하는 방법은 무엇입니까?

sourcejob 2023. 4. 24. 23:09
반응형

PowerShell에서 각 명령이 종료될 때까지 기다렸다가 다음 명령을 시작하도록 지시하는 방법은 무엇입니까?

PowerShell 1.0 스크립트를 사용하여 다양한 애플리케이션을 열 수 있습니다.첫 번째는 가상 머신이고 나머지 하나는 개발 어플리케이션입니다.나머지 애플리케이션을 열기 전에 가상 시스템의 부팅을 완료해야 합니다.

배쉬에서 나는 그냥 말할 수 있었다."cmd1 && cmd2"

이게 내가 가진...

C:\Applications\VirtualBox\vboxmanage startvm superdooper
    &"C:\Applications\NetBeans 6.5\bin\netbeans.exe"

일반적으로 내부 명령의 경우 PowerShell은 다음 명령을 시작하기 전에 대기합니다.이 규칙의 예외 중 하나는 외부 Windows 서브시스템 기반 EXE입니다.첫 번째 방법은 파이프라인을 통해 다음과 같이 하는 것입니다.

Notepad.exe | Out-Null

PowerShell은 메모장이 표시될 때까지 기다립니다.계속하기 전에 exe 프로세스가 종료되었습니다.그것은 훌륭하지만 코드를 읽어서 알아내기에는 좀 미묘하다.를 사용하여-Wait파라미터:

Start-Process <path to exe> -NoNewWindow -Wait

PowerShell Community Extensions 버전을 사용하는 경우 다음과 같습니다.

$proc = Start-Process <path to exe> -NoNewWindow -PassThru
$proc.WaitForExit()

PowerShell 2.0의 또 다른 옵션은 백그라운드 작업을 사용하는 것입니다.

$job = Start-Job { invoke command here }
Wait-Job $job
Receive-Job $job

를 사용하는 것 외에 실행 파일의 출력을 파이프로 연결하면 Powershell이 대기하게 됩니다.필요에 따라서는, 통상은, 또는 에 접속합니다.Out-String -Stream다음은 기타 출력 옵션의 긴 목록입니다.

# Saving output as a string to a variable.
$output = ping.exe example.com | Out-String

# Filtering the output.
ping stackoverflow.com | where { $_ -match '^reply' }

# Using Start-Process affords the most control.
Start-Process -Wait SomeExecutable.com

당신이 참조한 CMD/Bash 스타일의 연산자(&, &&, ||)가 그립습니다.우리는 파워셸에 대해 좀 더 장황하게 말해야 할 것 같다.

"Wait-process(대기 프로세스)"를 사용합니다.

"notepad","calc","wmplayer" | ForEach-Object {Start-Process $_} | Wait-Process ;dir

일이 끝났다

사용하시는 경우Start-Process <path to exe> -NoNewWindow -Wait

를 사용할 수도 있습니다.-PassThru옵션을 지정하여 출력을 에코합니다.

일부 프로그램은 파이프를 사용하여 출력 스트림을 잘 처리할 수 없습니다.Out-Null차단되지 않을 수 있습니다.
그리고.Start-Process필요한 것은-ArgumentList인수를 통과하도록 전환합니다. 그다지 편리하지 않습니다.
또 다른 접근법이 있습니다.

$exitCode = [Diagnostics.Process]::Start(<process>,<arguments>).WaitForExit(<timeout>)

옵션 포함-NoNewWindow에러가 표시됩니다.Start-Process : This command cannot be executed due to the error: Access is denied.

내가 그걸 작동시킬 수 있는 유일한 방법은 전화하는 거였어:

Start-Process <path to exe> -Wait

이 질문은 오래전에 한 질문입니다만, 여기의 답변은 참고 자료이기 때문에, 최신의 사용법을 언급할 수 있습니다.현재의 실장에서는PowerShell(그것은7.2 LTS(서면상)을 사용할 수 있습니다.&&에서 하듯이Bash.

좌측 파이프라인의 성공을 바탕으로 우측 파이프라인을 조건부로 실행합니다.

   # If Get-Process successfully finds a process called notepad,
   # Stop-Process -Name notepad is called
   Get-Process notepad && Stop-Process -Name notepad

문서 상세

더 나아가서 즉석에서 구문 분석할 수도 있습니다.

예.

& "my.exe" | %{
    if ($_ -match 'OK')
    { Write-Host $_ -f Green }
    else if ($_ -match 'FAIL|ERROR')
    { Write-Host $_ -f Red }
    else 
    { Write-Host $_ }
}

@Justin & @Nathan Hartley의 답변을 바탕으로 합니다.

& "my.exe" | Out-Null    #go nowhere    
& "my.exe" | Out-Default # go to default destination  (e.g. console)
& "my.exe" | Out-String  # return a string

파이프는 실시간으로 그것을 돌려줄 것이다.

& "my.exe" | %{    
   if ($_ -match 'OK')    
   { Write-Host $_ -f Green }    
   else if ($_ -match 'FAIL|ERROR')   
   { Write-Host $_ -f Red }   
   else    
   { Write-Host $_ }    
}

주의: 실행된 프로그램이 0 종료 코드 이외의 값을 반환할 경우 파이프는 작동하지 않습니다.다음과 같은 리다이렉션 연산자를 사용하여 강제로 파이프로 연결할 수 있습니다.2>&1

& "my.exe" 2>&1 | Out-String

출처:

https://stackoverflow.com/a/7272390/254276

https://social.technet.microsoft.com/forums/windowsserver/en-US/b6691fba-0e92-4e9d-aec2-47f3d5a17419/start-process-and-redirect-output-to-powershell-window

cmd는 항상 있어요.

cmd /c start /wait notepad

또는

notepad | out-host

언급URL : https://stackoverflow.com/questions/1741490/how-to-tell-powershell-to-wait-for-each-command-to-end-before-starting-the-next

반응형