Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell - Overwriting line written with Write-Host

Tags:

powershell

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

like image 293
developer82 Avatar asked Sep 15 '14 11:09

developer82


People also ask

What is the difference between write-host and write-output in PowerShell?

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.

What does %% mean in PowerShell?

% is an alias for the ForEach-Object cmdlet. An alias is just another name by which you can reference a cmdlet or function.

How do you go up a line in PowerShell?

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.

What does write-host do?

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.


2 Answers

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

like image 172
Raf Avatar answered Sep 29 '22 15:09

Raf


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 
like image 45
Dullson Avatar answered Sep 29 '22 14:09

Dullson