How to check the incoming command is multi-line in PowerShell?

42 Views Asked by At

I create an idle-check code in Prompt function using [console]::KeyAvailable like this:

function Prompt{
   # some code

   $continue = $false
   while ($continue) {
      if ([console]::KeyAvailable) {
          $continue = $true
      }
      Start-Sleep -Milliseconds 10
      # do something
   }

   return ">"
}

It works properly as I intended, so when the user is idle, the script will do something, and when any key is typed, It'll exit the loop.

The problem is when I type Enter twice, the first one will be executed properly, but the second won't. The process is stuck in the loop. Or, when I paste a multi-line command from the clipboard, it behaves the same.

Is there a way to detect the incoming input? So I can add additional conditions to the loop.

I tried using [console]::ReadLine but it's not reading from the previously executed line but the new user input.

1

There are 1 best solutions below

1
Ruben Murrin On

In PowerShell the Prompt function isn't really cut out for complex input handling like detecting multi-line commands. Your current setup with [console]::KeyAvailable checks for any key press but it doesnt differentiate between keys or deal well with multiline inputs.

maybe try this

function Prompt {

    while (-not [console]::KeyAvailable) {
        Start-Sleep -Milliseconds 10
    }
    $null = [System.Console]::ReadKey($true)

    return ">" 
}

A custom input function or a different tool is probably better for anything more complicated.