Is there a way to return to the command prompt temporarily

305 Views Asked by At

How would One allow users to "Pause the current Pipeline and return to the command prompt" and later resume in a powershell script?

I stumbled upon this line in a blog post about User Interaction in Powershell

$suspend = New-Object System.Management.Automation.Host.ChoiceDescription "&Suspend", "Pause the current pipeline and return to the command prompt. Type ""exit"" to resume the pipeline."

It was a mock option in a prompt imitating the appearance of a native command (Remove-Item). Lo and behold: That command actually Implements that behavior. Doing a quick Google Search, I did not find an implementation in a script.

2

There are 2 best solutions below

1
Mathias R. Jessen On BEST ANSWER

You can use $Host.EnterNestedPrompt() to suspend the current operation to enter a "nested" prompt - execution will resume once you exit it (using either exit or $Host.ExitNestedPrompt()):

function f {
  param([switch]$Intervene)

  $abc = 123

  if($Intervene.IsPresent){
    $host.EnterNestedPrompt()
  }

  Write-Host "`$abc has value '$abc'"
}

Now try invoking the function with and without the -Intervene switch:

enter image description here

0
mklement0 On

Mathias R. Jessen's helpful answer is undoubtedly the best solution for your use case.

Because there is functional overlap, let me offer a solution for on-demand debugging of a script or function, using the Wait-Debugger cmdlet, which also enters a nested prompt in the current scope, while offering additional, debugging-specific functionality to step through the code.

function foo {
  'Entering foo.'
  if (0 -eq $host.ui.PromptForChoice('Debugging', 'Enter the debugger?', ('&Yes', '&No'), 1)) {
    Wait-Debugger
  }
  'Exiting foo.'
}

Executing foo presents a yes/no prompt for whether the debugger should be entered.

The debugging prompt can be exited with exit or simply c (one of the debugging-specific commands; h shows them all).