2

Let's say you have the following script saved in a file outermost.ps1:

powershell.exe -Command "while ( 1 -eq 1 ) {} "
echo "Done"

When running outermost.ps1 you can only abort this by pressing Ctrl+C, and no output will be written to console. How can I modify it so that the outermost script continues and executes echo "Done" when Ctrl+C is pressed?

This is a simplified version of a real-life scenario where the inner script is actually an executable which only is stoppable by pressing Ctrl+C.

Edit: The script could also be:

everlooping.exe
echo "Done"

but I wanted to provide an example everyone could copy-paste into an editor if they wanted to "try at home".

6
  • whats the point in having "powershell.exe -Command " in a powershell script? Commented Jan 5, 2016 at 11:52
  • See my comment in paranthesis. The actual outermost.ps1looks more like Line 1: somestupid.exe, Line 2: Echo "done" Commented Jan 5, 2016 at 11:53
  • so no "powershell.exe -Command " after all? Commented Jan 5, 2016 at 11:54
  • So your question is really: "How can I interrupt an executable invoked inside a powershell script?" Commented Jan 5, 2016 at 11:54
  • 3
    for a start: Get-Help Start-Process -full Commented Jan 5, 2016 at 11:57

2 Answers 2

4

Start your infinite command/statement as a job, make your PowerShell script process Ctrl+C as regular input (see here), and stop the job when that input is received:

[Console]::TreatControlCAsInput = $true

$job = Start-Job -ScriptBlock {
  powershell.exe -Command "while ( 1 -eq 1 ) {} "
}

while ($true) {
  if ([Console]::KeyAvailable) {
    $key = [Console]::ReadKey($true)
    if (($key.Modifiers -band [ConsoleModifiers]::Control) -and $key.Key -eq 'c') {
      $job.StopJob()
      break
    }
  }
  Start-Sleep -Milliseconds 100
}

Receive-Job -Id $job.Id
Remove-Job -Id $job.Id

echo "Done"

If you need to retrieve output from the job while it's running, you can do so like this in an else branch to the outer if statement:

if ($job.HasMoreData) { Receive-Job -Id $job.Id }
Sign up to request clarification or add additional context in comments.

Comments

0

The simplest solution to this is:

    Start-Process -Wait "powershell.exe" -ArgumentList "while ( 1 -eq 1 ) {}"
    echo "Done"

This will spawn a second window unlinke ansgar-wiechers solution, but solves my problem with the least amount of code.

Thanks to Jaqueline Vanek for the tip

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.