
質問
script.ps1
で PowerShell コマンド(たとえば、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
開いたまま閉じません。