powershellcommand-line-interfaceuser-interaction

Is there a way to return to the command prompt temporarily


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.


Solution

  • 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