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
In a nutshell, Write-Host writes to the console itself. Think of it as a MsgBox in VBScript. Write-Output , on the other hand, writes to the pipeline, so the next command can accept it as its input. You are not required to use Write-Output in order to write objects, as Write-Output is implicitly called for you.
% is an alias for the ForEach-Object cmdlet. An alias is just another name by which you can reference a cmdlet or function.
To move to the beginning of a line, press Home . To move to the end of a line, press End . If lines were added, press Home or End twice to move to the beginning or end of the lines.
Starting in Windows PowerShell 5.0, Write-Host is a wrapper for Write-Information This allows you to use Write-Host to emit output to the information stream. This enables the capture or suppression of data written using Write-Host while preserving backwards compatibility.
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
As a tweak to Raf's answer above, You don't have to wipe the screen every time to update your last line. Calling Write-Host
with -NoNewLine
and carriage return `r
is enough.
for ($a=0; $a -le 100; $a++) { Write-Host -NoNewLine "`r$a% complete" Start-Sleep -Milliseconds 10 } Write-Host #ends the line after loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With