1

Question

How can I execute a powershell command in a script.ps1 (that for example starts an infinite loop in a WSL), wait 5 seconds, and then stop/break that command so that powershell moves to the next line of the script.ps1?

Example behavior

If I manually press ctrl+c when the command is engaged in powershell, it stops the wsl command, and prints the output of the command/continues with line Write-Host "output="$output.

Attempts

  1. Emulating sending ctrl+c to the powershell terminal.
# 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

But that keeps hanging in the first command and does not continue to show the output.

  1. Putting the command in a job, and terminating that job after n seconds.
# 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

The command is executed, but not terminated.

  1. Based on the comments, I used start-process to run the code in a separate window, which works. I am currently determining how to get the object that is started, so that I can apply/call Stop-Process on it.
$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"

Which indeed continues and says it stopped the process, but the window of the wsl is still opened afterwards and does not close.

2
  • 2
    you may need to use Start-Process since that defaults to "keep going". then add a loop that does your other work and checks to see if the process is still running. you can use the system stopwatch for your timer. [grin]
    – Lee_Dailey
    Commented Aug 26, 2019 at 13:28
  • In your 2nd attempt, the background command (start-sleep 2), is shorter than the time out. Wouldn't the correct test be to make this longer than the timeout? I ran that example with start-sleep 60 and it worked as expected. When script completes, get-job shows it as stopped
    – uSlackr
    Commented Jul 25, 2022 at 15:54

0

You must log in to answer this question.

Browse other questions tagged .