TheAschr
TheAschr

Reputation: 973

Powershell carriage return not working

$startTime = $(get-date)
write-host "`rElapsed:00:00:00"
$NoEvent = $true
While ($NoEvent)
{
  Start-Sleep 1
  $elapsedTime = new-timespan $startTime $(get-date)
  write-host "`rElapsed:$($elapsedTime.ToString('hh\:mm\:ss'))"
  #Handle event
  if(event){$NoEvent = $false}
}

I've tried running this in the ISE as well as through the regular console. The returns are never output.

Upvotes: 0

Views: 2506

Answers (3)

ShanayL
ShanayL

Reputation: 1247

I don't think there is any PS cmdlet that can help with overwriting text from the same line unless you are clearing the entire window with clear-host or cls, but PowerShell has a built in write-progress cmdlet if that is something else you would want to consider.

You can try:

$startTime = $(get-date)
$NoEvent = $true
While ($NoEvent)
{

    for ($a=1; $a -lt 100; $a++) {

        Start-Sleep 1
        $elapsedTime = new-timespan $startTime $(get-date)

        Write-Progress -Activity "`rElapsed:$($elapsedTime.ToString('hh\:mm\:ss'))" -PercentComplete $a -CurrentOperation "$a% Processed" -Status "Please wait."

        #Handle event
        if(event){$NoEvent = $false}
    }
}

See: https://learn.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Write-Progress?view=powershell-5.1 for info on write-progress

and here is a related question: PowerShell - Overwriting line written with Write-Host

Upvotes: 0

TheAschr
TheAschr

Reputation: 973

I eventually got it working using -NoNewLine switch

write-host -NoNewLine "`rElapsed:$($elapsedTime.ToString('hh\:mm\:ss'))"

Upvotes: 1

Jeff Zeitlin
Jeff Zeitlin

Reputation: 10809

`r only issues a CR, not a CR+LF (which is probably what you want). Use `n (‘newline’) instead.

Upvotes: 0

Related Questions