windowspowershellterminalwindows-console

Printing text on the same line as previous input


This is essentially what I want to do:

Write-Host "Enter username: " -NoNewLine
$username = Read-Host -NoNewLine
if ($username -eq "") {
    Write-Host "None"
}

If the user were to enter nothing, then this would be my desired output: Enter username: None

However I have been unable to find a way to read user input without it generating a new line, and -NoNewLine does not work with Read-Host.


Solution

  • You should be able to do this by first recording the position of the terminal's cursor using the PSHostRawUserInterface.CursorPosition property, which can be found at $host.UI.RawUI.CursorPosition

    After prompting for the username and determining that it's blank, reset the cursor back to its original position and then output the desired text.

    Example code:

    # Output the prompt without the new line
    Write-Host "`rEnter username: " -NoNewLine
    
    # Record the current position of the cursor 
    $originalPosition = $host.UI.RawUI.CursorPosition
    
    # Prompt for the username
    $username = Read-Host
    
    # Check the response with the IsNullOrWhiteSpace function to also account for empty strings
    if ([string]::IsNullOrWhiteSpace($username)) {
        # Set the position of the cursor back to where it was before prompting the user for a response
        [Console]::SetCursorPosition($originalPosition.X,$originalPosition.Y)
    
        # Output the desired text
        Write-Host "None"
    }