Home > other >  Line break after output in Powershell or Terminal
Line break after output in Powershell or Terminal

Time:09-04

Is there a way to have a line break after the output in Powershell, or in Windows Terminal?

enter image description here

In my profile I added Write-Host but then there is a line break before the prompt including the first line (when terminal starts) which I don't want:

function prompt
{
  Write-Host
  Write-Host
}

enter image description here

I tried a conditional but it doesn't work:

function prompt
{
  $first = $true
  if ($first) {$first = $false}
  else {Write-Host}
  Write-Host
}

CodePudding user response:

  • To prevent the initial prompt after startup from printing empty lines, check if the session's command history is empty, using Get-History.

  • To additionally prevent unwanted empty lines after clearing the screen (e.g. with Clear-Host), you can test the index of the current line of the cursor with $host.ui.rawUI.cursorPosition.Y, as suggested by Luuk, or, more simply in a console (terminal), with [Console]::CursorTop:

function prompt { 
  if ([Console]::CursorTop -gt 0 -and (Get-History -Count 1)) { 
    Write-Host "`n" 
  } else { # initial prompt or after clearing the screen
    '' 
  } 
}

Note:

  • The approach relies on the fact that PowerShell prints its default prompt string, PS>, if the prompt function produces either no or empty output to the success stream, which happens after any (by definition success-stream-bypassing) output from Write-Host has printed.

  • If you simply want to emit an empty line in combination with the current prompt function, use the following:

$function:prompt = @"
  if ([Console]::CursorTop -gt 0 -and (Get-History -Count 1)) { 
    Write-Host "`n" 
  } 
  $function:prompt
"@ 

CodePudding user response:

Edit: (might still not get the question) but this will add an extra line break

Write-Host "Hellow World!`n"

If this is related to starting a new powershell window, try Clear-Host at the top of your profile script

  • Related