Update the write-host output in Powershell

Update the write-host output in Powershell

Update the write-host output in Powershell is something I’ve been researching and all I could find where just a few answers on forums but nothing documented by technet nor in other blogs.
By “Update the write-host output in Powershell” I mean to actually replace what’s written in console without adding a new line.

For instance you want the console to update every second. See the example below:

start-sleep -seconds 1
Write-Host "`rScript started 1 seconds ago." -NoNewLine
start-sleep -seconds 1
Write-Host "`rScript started 2 seconds ago." -NoNewLine
start-sleep -seconds 1
Write-Host "`rScript started 3 seconds ago." -NoNewLine
start-sleep -seconds 1


4..15 | %{
	
	Write-Host "`rScript started $_ seconds ago." -NoNewLine
	start-sleep -seconds 1

}

Write-Host "`rScript started 16 seconds ago." -NoNewLine

Very simple to understand: you need `r and -NoNewLine so that you keep writing on the same line. In the example above you can clearly see how convenient this is in a cycle as well as in a standard output across the script.
Remember that after the latest -NoNewLine, you will have to add a carriage return to get the extra text in a new line.

You better use write-progress if you’re able to identify the target. By target I mean the number of items your cycle has to go through so that you can build a scale 0-100 based on that number. If you have a cycle that is repeated 200 times (TotalItems), the 1st item will be 0.5%. To do that in a script you could use this formula:

Counter/TotalItems*100

For instance, if you have 50 items and the counter is at 2:

2/50*100 = 4

Your progress will be at 4%.

This is the link to technet for write-progress: https://technet.microsoft.com/en-us/library/hh849902.aspx

IT Droplets

IT Droplets