Home > Mobile >  Printing text on the same line as previous input
Printing text on the same line as previous input

Time:06-19

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.

CodePudding user response:

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"
}

CodePudding user response:

That is because there is no '-NoNewLinew' switch for Read-Host. As per MS PS docs.

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/read-host?view=powershell-7.2

Read-Host
    [[-Prompt] <Object>]
    [-MaskInput]
    [<CommonParameters>]

There is for Write-Host.

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/write-host?view=powershell-7.2

Write-Host
     [[-Object] <Object>]
     [-NoNewline]
     [-Separator <Object>]
     [-ForegroundColor <ConsoleColor>]
     [-BackgroundColor <ConsoleColor>]
     [<CommonParameters>]

Why overcomplicate this use case. Why not simply do something like this:

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

Unless you're using a Write-Host switch or color, it's not really needed, since the buffer will dump to the screen by default.

Or maybe something like this, to force input.

Clear-Host
$Name = ''
Do {
    $Name = Read-Host -Prompt 'Enter username'
}
While ($Name -EQ '')
"Welcome $Name"
  • Related