问题
如何在中执行 powershell 命令script.ps1
(例如在 WSL 中启动无限循环),等待 5 秒,然后停止/中断该命令,以便 powershell 移动到下一行script.ps1
?
示例行为
如果我在 powershell 中使用命令时手动按下ctrl+c
,它会停止 wsl 命令,并打印命令的输出/继续第 行Write-Host "output="$output
。
尝试
- 模拟发送
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
但它一直挂在第一个命令上并且不会继续显示输出。
- 将命令放入作业中,并在
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
命令已执行,但未终止。
- 根据评论,我使用 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
仍然打开并且不会关闭。