n초 후에 powershell 명령을 중지하는 방법은 무엇입니까?

n초 후에 powershell 명령을 중지하는 방법은 무엇입니까?

질문

script.ps1(예를 들어 WSL에서 무한 루프를 시작하는) powershell 명령을 실행하고 5초를 기다린 후 해당 명령을 중지/중단하여 powershell이 ​​의 다음 줄로 이동하도록 하려면 어떻게 해야 합니까 script.ps1?

예시 동작

명령이 powershell에 사용될 때 수동으로 누르면 ctrl+cwsl 명령이 중지되고 명령 출력이 인쇄됩니다/line 으로 계속됩니다 Write-Host "output="$output.

시도

  1. ctrl+cPowershell 터미널로 전송을 에뮬레이션합니다 .
# line 1, activate "inifinite" loop in wsl
[String] $output = wsl /home/testlinuxname/maintenance/gCal/./askSync.sh

# try to stop/break the previous command/infinite loop
[void][System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
[System.Windows.Forms.SendKeys]::SendWait("^{c}") 

# get the output of the first command and print it to screen.
Write-Host "output="$output

그러나 첫 번째 명령에서는 계속 중단되고 출력이 계속 표시되지 않습니다.

  1. 명령을 작업에 넣고 n몇 초 후에 해당 작업을 종료합니다.
# Start Job
$job = Start-Job -ScriptBlock {
    Start-Sleep -Seconds 2
}

# Wait for job to complete with timeout (in seconds)
$job | Wait-Job -Timeout 10

# Check to see if any jobs are still running and stop them
#$job | Where-Object {(wsl pwd > c:/temp/output.txt) } | Stop-Job #Executes command and puts it in log
$job | Where-Object {(wsl /home/testlinuxname/maintenance/gCal/./askSync.sh > c:/temp/output.txt) } | Stop-Job # Execute command but does not terminate

명령이 실행되지만 종료되지는 않습니다.

  1. 의견을 바탕으로 start-process를 사용하여 별도의 창에서 코드를 실행했습니다. 이는 작동합니다. 현재 시작된 개체를 가져오는 방법을 결정 중이므로 Stop-Process해당 개체에 적용/호출할 수 있습니다.
$proc = Start-Process wsl /home/testlinuxname/maintenance/gCal/./askSync.sh > c:/temp/output.txt -RedirectStandardOutput c:/temp/input1.txt -Passthru
Write-Host "Continuing powershell and starting sleep:"
Start-Sleep -s 10
Write-Host "Done sleeping, now stopping process:"
$proc | Stop-Process
Write-Host "Stopped process"

실제로 계속되고 프로세스가 중지되었다고 표시되지만 이후에도 창은 wsl계속 열려 있고 닫히지 않습니다.

관련 정보