powershell

PowerShell - Overwriting line written with Write-Host


I'm trying to overwrite a line in PowerShell written with Write-Host (I have a process that's running in a loop and I want to show percentage updated on the screen). What I've tried to do is this:

Write-Host -NoNewline "`rWriting $outputFileName ($i/$fileCount)... $perc%"

but instead of overwriting the line it stays on the same line and appends to it.

what am I missing here?

Thanks


Solution

  • You cannot overwrite a line in a Powershell window. What you can do is blank the window with cls(Clear-Host):

    # loop code
    cls
    Write-Host "`rWriting $outputFileName ($i/$fileCount)... $perc%"
    # end loop
    

    But what you should really be using is Write-Progress, a cmdlet built specifically for this purpose:

    # loop code
    Write-Progress -Activity "Writing $outputFileName" -PercentComplete $perc
    # end loop
    

    More on Write-Progress here: http://technet.microsoft.com/en-us/library/hh849902.aspx