如何在n秒後停止powershell指令?

如何在n秒後停止powershell指令?

問題

如何在 a 中執行 powershell 命令script.ps1(例如在 WSL 中啟動無限循環),等待 5 秒,然後停止/中斷該命令,以便 powershell 移動到 a 的下一行script.ps1

行為範例

如果我在 powershell 中執行該命令時手動按下ctrl+c,它會停止 wsl 命令,並列印命令的輸出/繼續 line Write-Host "output="$output

嘗試

  1. 類比發送ctrl+c到 powershell 終端。
# 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仍然打開並且不會關閉。

相關內容