How can I increase the maximum number of characters read by Read-Host? - powershell

I need to get a very long string input (around 9,000 characters), but Read-Host will truncate after around 8,000 characters. How can I extend this limit?

The following are possible workarounds.
Workaround 1 has the advantage that it will work with PowerShell background jobs that require keyboard input. Note that if you are trying to paste clipboard content containing new lines, Read-HostLine will only read the first line, but Read-Host has this same behavior.
Workaround 1:
<#
.SYNOPSIS
Read a line of input from the host.
.DESCRIPTION
Read a line of input from the host.
.EXAMPLE
$s = Read-HostLine -prompt "Enter something"
.NOTES
Read-Host has a limitation of 1022 characters.
This approach is safe to use with background jobs that require input.
If pasting content with embedded newlines, only the first line will be read.
A downside to the ReadKey approach is that it is not possible to easily edit the input string before pressing Enter as with Read-Host.
#>
function Read-HostLine ($prompt = $null) {
if ($prompt) {
"${prompt}: " | Write-Host
}
$str = ""
while ($true) {
$key = $host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown");
# Paste the clipboard on CTRL-V
if (($key.VirtualKeyCode -eq 0x56) -and # 0x56 is V
(([int]$key.ControlKeyState -band [System.Management.Automation.Host.ControlKeyStates]::LeftCtrlPressed) -or
([int]$key.ControlKeyState -band [System.Management.Automation.Host.ControlKeyStates]::RightCtrlPressed))) {
$clipboard = Get-Clipboard
$str += $clipboard
Write-Host $clipboard -NoNewline
continue
}
elseif ($key.VirtualKeyCode -eq 0x08) { # 0x08 is Backspace
if ($str.Length -gt 0) {
$str = $str.Substring(0, $str.Length - 1)
Write-Host "`b `b" -NoNewline
}
}
elseif ($key.VirtualKeyCode -eq 13) { # 13 is Enter
Write-Host
break
}
elseif ($key.Character -ne 0) {
$str += $key.Character
Write-Host $key.Character -NoNewline
}
}
return $str
}
Workaround 2:
$maxLength = 65536
[System.Console]::SetIn([System.IO.StreamReader]::new([System.Console]::OpenStandardInput($maxLength), [System.Console]::InputEncoding, $false, $maxLength))
$s = [System.Console]::ReadLine()
Workaround 3:
function Read-Line($maxLength = 65536) {
$str = ""
$inputStream = [System.Console]::OpenStandardInput($maxLength);
$bytes = [byte[]]::new($maxLength);
while ($true) {
$len = $inputStream.Read($bytes, 0, $maxLength);
$str += [string]::new($bytes, 0, $len)
if ($str.EndsWith("`r`n")) {
$str = $str.Substring(0, $str.Length - 2)
return $str
}
}
}
$s = Read-Line
More discussion here:
Console.ReadLine() max length?
Why does Console.Readline() have a limit on the length of text it allows?
https://github.com/PowerShell/PowerShell/issues/16555

Related

Powershell - Fix Line Break

I have a situation here and I would like to share it with you to ask for help.
I have a TXT file that I receive every day and I need to import it into my ERP, however, this file comes with a line break that we have to manually adjust
And when adjusted, it looks like this:
{
Write-Error "Informe um arquivo para leitura"
Return
}
$arquivo = $args[0]
if(![System.IO.File]::Exists($arquivo))
{
Write-Error "Arquivo nao encontrado: $arquivo"
Return
}
$tamanhoEsperado = 240
$ultimoTamanho = 0
foreach($linha in [System.IO.File]::ReadLines($arquivo))
{
if ($linha.length -gt 0)
{
if (!($linha.length -eq $tamanhoEsperado) -And (($linha.length + $ultimoTamanho) -eq $tamanhoEsperado))
{
Write-Host -NoNewLine $linha
$ultimoTamanho += $linha.length
}
else
{
if ($ultimoTamanho -gt 0)
{
Write-Host
}
Write-Host -NoNewLine $linha
$ultimoTamanho = $linha.length
}
}
else
{
Write-Host
}
}
But I am not able to make the process automatic with this script.
Powershell will look for the TXT file in a specific folder, validate if the file has 240 positions and if not, correct that line break shown in img1. Would that be possible?
Note:
Write-Host is typically the wrong tool to use, unless the intent is to write to the display only, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, or redirect it to a file. To output a value, use it by itself; e.g., $value instead of Write-Host $value (or use Write-Output $value). See this answer for more information.
Therefore, your code only produced for-display output, not data.
Try something like the following:
$fragment = ''
$correctedLines =
foreach ($line in [System.IO.File]::ReadLines($arquivo)) {
if ($fragment) { # The previous line was incomplete.
$fragment + $line # Concatenate the fragment with the current line and output.
$fragment = '' # Reset the fragment variable.
} elseif ($line.Length -ne 240) {
$fragment = $line # Save the fragment and continue.
} else {
$line # Complete line -> output it.
}
}
Note the use of implicit output (e.g., $line) and that you can directly collect all output from the foreach statement in a variable.

User input validation in PowerShell

I have this piece of code in PowerShell. I need user input validation to integer with writing output saying what is wrong with the input and expecting correct input.
$FromObj = "Please input object number"
$FromInput = Read-Host $FromObj
while(($FromInput -isnot [int])) {
#I also want to put in the while that the input has to be an integer, -gt 0, and -lt 800
Write-Output "Your input has to be a number."
$FromInput = Read-Host $FromObj
}
if ($FromInput -le 0) {
Write-Output "Your input has to be a number greater than 0!"
$FromInput = Read-Host $FromObj
}
elseif ($FromInput -ge 800) {
Write-Output "Your input has to be a number less than 800!"
$FromInput = Read-Host $FromObj
}
else {
$FromInput = $FromInput -as [int]
}
However, this is not working for me. Could you help me with validating it with writing outputs as the ones displayed above?
I think Nicks's link in comment already provides different right answers to your question i.e.: using regex to match \d+ (digits) or using [int]::TryParse(...) but to explain why your code is not working:
Read-Host will store user input as string unless you manipulate it which is what you were already doing on your last condition (the else {...} statement).
This is why you never get past the $FromInput -isnot [int] condition.
To fix the code you could simply attempt to store user input -as [int] since the beginning and since you have 3 Read-Host on your code you could save the user input attempt -as [int] in a ScriptBlock which then can be easily executed as many times as needed:
$FromObj = "Please input object number"
$giveMeNumber = { (Read-Host $FromObj) -as [int] }
$FromInput = & $giveMeNumber
while($FromInput -isnot [int]) {
Write-Output "Your input has to be a number."
$FromInput = & $giveMeNumber
}
if ($FromInput -le 0) {
Write-Output "Your input has to be a number greater than 0!"
$FromInput = & $giveMeNumber
}
elseif ($FromInput -ge 800) {
Write-Output "Your input has to be a number less than 800!"
$FromInput = & $giveMeNumber
}
Note, even though this works, the statement is not entirely correct since you're breaking out of the while loop after the input is [int] the user could force an incorrect input.
Try this instead which will execute indefinitely until right input:
Clear-Host
$ErrorActionPreference = 'Stop'
$FromObj = "Please input object number"
$scriptBlock = {
try
{
$FromInput = [int](Read-Host $FromObj)
# Note I'm using Write-Host instead of Write-Ouput, this is because
# we don't want to store the invalid inputs messages in the
# $userInput variable.
if ($FromInput -le 0) {
Write-Host "Your input has to be a number greater than 0!"
& $scriptBlock
}
elseif ($FromInput -ge 800) {
Write-Host "Your input has to be a number less than 800!"
& $scriptBlock
}
else {
$FromInput
}
}
catch
{
Write-Host "Your input has to be a number."
& $scriptBlock
}
}
$userInput = & $scriptBlock

Find variables within a string in PowerShell

I've a sample code like this:
[string] $Text = "This is a string text with some $($variable.Option) and $otherOption and that's it".
Now what I would like to know is it possible to split that $Text into standard strings and variables separately? So that when I pass this $Text variable to a method it's able to extract $($variable.Option) separately?
I know it's a long shot but maybe it's not being processed right away at assignment time?
The ultimate goal is to create a better version of method I wrote for making colorful powershell:
function Write-Color([String[]]$Text, [ConsoleColor[]]$Color = "White", [int]$StartTab = 0, [int] $LinesBefore = 0,[int] $LinesAfter = 0) {
$DefaultColor = $Color[0]
if ($LinesBefore -ne 0) { for ($i = 0; $i -lt $LinesBefore; $i++) { Write-Host "`n" -NoNewline } } # Add empty line before
if ($StartTab -ne 0) { for ($i = 0; $i -lt $StartTab; $i++) { Write-Host "`t" -NoNewLine } } # Add TABS before text
if ($Color.Count -ge $Text.Count) {
for ($i = 0; $i -lt $Text.Length; $i++) { Write-Host $Text[$i] -ForegroundColor $Color[$i] -NoNewLine }
} else {
for ($i = 0; $i -lt $Color.Length ; $i++) { Write-Host $Text[$i] -ForegroundColor $Color[$i] -NoNewLine }
for ($i = $Color.Length; $i -lt $Text.Length; $i++) { Write-Host $Text[$i] -ForegroundColor $DefaultColor -NoNewLine }
}
Write-Host
if ($LinesAfter -ne 0) { for ($i = 0; $i -lt $LinesAfter; $i++) { Write-Host "`n" } } # Add empty line after
}
Usually I can assign colors by doing something like
write-color -Text "[View][$($singleView.Title)]",
"[Row Limit: $($singleView.RowLimit)]",
"[Paged: $($singleView.Paged)]",
"[Default View: $($singleView.DefaultView)]",
"[Style ID: $($singleView.StyleID)]" -Color Yellow, Green, Red, Gray, Green
But this means I get colors for the whole "line". If i would like to get normal text colors in one color and variables being in second color I would have to do something like this:
write-color -Text "[View: ", "$($singleView.Title)", "]",
"[Row Limit: ", "$($singleView.RowLimit)", "]" `
-Color Yellow, Green, Yellow, Yellow, Green, Yellow
It's not bad.. but I just thought if this can be accomplished in a better way where simple text is one color and variables are the 2nd. If I would want to go even further and have $true being in Green and False being in Red that would also require some parsing.
Variables will expand inside double quotes. Once that is done there is no history to speak of.
You have one of two options here. You can use the format operator to send in string with placeholders for your variables.
Use the format operator
ss64 on Using the format operator
# Create a formatted string with variable placeholders
$Text = "This is a string text with some {0} and {1} and that's it"
# Pass that string into a function and put in the variables
$stringParameterinFunction -f $variable.Option, $otherOption
String Expansion
If you really wanted what I think you are asking for then you can delay the string expansion by use single quotes on the original string. Note the single quote inside the string was escaped.
$Text = 'This is a string text with some $($variable.Option) and $otherOption and that''s it.'
# Pass that string into a function and put in the variables
$ExecutionContext.InvokeCommand.ExpandString($stringParameterinFunction)

strange characters when opening a properties file

I have a requirement to update a properties file for a very old project, the properties file is supposed to display Arabic characters but it displays somthing like that "Êã ÊÓÌíá ØáÈßã", i wrote a simple program from which i was able to read the correct Arabic values from the file,
Reader r = new InputStreamReader(new FileInputStream("C:\\Labels_ar.properties"), "Windows-1256");
buffered = new BufferedReader(r);
String line;
while ((line = buffered.readLine()) != null) {
System.out.println("line" + line);
}
but do u have any idea on how i can open the file, edit and save the new changes?
If, as you seem to think, the encoding is Windows-1256, there are editors that will do the job, such as EditPadLite.
If it's not that, the first thing you need to find out is the encoding. Given it's a properties file, it may well be UTF-8 but the easiest way to find out is to get a hex dump of the file and post it here. Under Linux, I'd normally suggest using:
od -xcb Labels_ar.properties
but, given you're on Windows, that's not going to work so well (unless you have CygWin installed).
So, if you have your own favourite hex dump program, just use that. Otherwise you can use the following Powershell one:
function Pf-Dump-Hex-Item([byte[]] $data) {
$left = "+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F"
$right = "0123456789ABCDEF"
Write-Output "======== $left +$right"
$addr = 0
$left = "{0:X8} " -f $addr
$right = ""
# Now go through the input bytes
foreach ($byte in $bytes) {
# Add 2-digit hex number then filtered character.
$left += "{0:x2} " -f $byte
if (($byte -lt 0x20) -or ($byte -gt 0x7e)) { $byte = "." }
$right += [char] $byte
# Increment address and start new line if needed.
$addr++;
if (($addr % 16) -eq 0) {
Write-Output "$left $right"
$left = "{0:X8} " -f $addr
$right = "";
}
}
# Flush last line if needed.
$lastLine = "{0:X8}" -f $addr
if (($addr % 16) -ne 0) {
while (($addr % 16) -ne 0) {
$left += " "
$addr++;
}
Write-Output "$left $right"
}
Write-Output $lastLine
Write-Output ""
}
function Pf-Dump-Hex {
param(
[Parameter (Mandatory = $false, Position = 0)]
[string] $Path,
[Parameter (Mandatory = $false, ValueFromPipeline = $true)]
[Object] $Object
)
begin {
Set-StrictMode -Version Latest
# Create the array to hold content then do path if given.
[byte[]] $bytes = $null
if ($Path) {
$bytes = [IO.File]::ReadAllBytes((Resolve-Path $Path))
Pf-Dump-Hex-Item $bytes
}
}
process {
# Process each object (input/pipe).
if ($object) {
foreach ($obj in $object) {
if ($obj -is [Byte]) {
$bytes = $obj
} else {
$inpStr = [string] $obj
$bytes = [Text.Encoding]::Unicode.GetBytes($inpStr)
}
Pf-Dump-Hex-Item $bytes
}
}
}
}
If you load that into a Powershell session then run:
pf-dump-hex Labels_ar.properties
that should allow you to evaluate the file encoding.
I think there are two problems :
1- Im not sure if System.out.println() can print arabic characters, so try another method like MessageBox.show() to be sure there is a problem with reading file.
2- If MessageBox.show() shows same result, the problem should be the charset, you can try UTF-8 or somthing else.

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
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
It not perfect but here is a script which has a spinning character in place. The part that lets you do this is:
$origpos = $host.UI.RawUI.CursorPosition
$origpos.Y += 1
Get the current position and save it so that we can keep referring to it. As you progress you change the $host.UI.RawUI.CursorPosition. Since it was previously saved you can reset it back $host.UI.RawUI.CursorPosition = $origpos. You should be able to experiment with that.
$scroll = "/-\|/-\|"
$idx = 0
$job = Invoke-Command -ComputerName $env:ComputerName -ScriptBlock { Start-Sleep -Seconds 10 } -AsJob
$origpos = $host.UI.RawUI.CursorPosition
$origpos.Y += 1
while (($job.State -eq "Running") -and ($job.State -ne "NotStarted"))
{
$host.UI.RawUI.CursorPosition = $origpos
Write-Host $scroll[$idx] -NoNewline
$idx++
if ($idx -ge $scroll.Length)
{
$idx = 0
}
Start-Sleep -Milliseconds 100
}
# It's over - clear the activity indicator.
$host.UI.RawUI.CursorPosition = $origpos
Write-Host 'Complete'
Remove-Variable('job')
$job = Start-Job -ScriptBlock { Start-Sleep -Seconds 10 }
while (($job.State -eq "Running") -and ($job.State -ne "NotStarted"))
{
Write-Host '.' -NoNewline
Start-Sleep -Seconds 1
}
Write-Host ""
So as log as you remember where you want to go back to then you can use this logic. This will not work properly in ISE. You can also use `b as a back space character as well.
I know, thats quite old, but i was in the same Situation und modified the Solution from Boluwade Kujero, just because writing blank lines before writing the new output may result in a "flickering" output.
So in the following function, I just do overwrite the existing line, write blanks until reaching the old cursorposition, and go back to the last character of the new line.
In addition i added an optical progressbar. Progress is calculated by the function through given Parameters:
function Write-Status
{
param([int]$Current,
[int]$Total,
[string]$Statustext,
[string]$CurStatusText,
[int]$ProgressbarLength = 35)
# Save current Cursorposition for later
[int]$XOrg = $host.UI.RawUI.CursorPosition.X
# Create Progressbar
[string]$progressbar = ""
for ($i = 0 ; $i -lt $([System.Math]::Round($(([System.Math]::Round(($($Current) / $Total) * 100, 2) * $ProgressbarLength) / 100), 0)); $i++) {
$progressbar = $progressbar + $([char]9608)
}
for ($i = 0 ; $i -lt ($ProgressbarLength - $([System.Math]::Round($(([System.Math]::Round(($($Current) / $Total) * 100, 2) * $ProgressbarLength) / 100), 0))); $i++) {
$progressbar = $progressbar + $([char]9617)
}
# Overwrite Current Line with the current Status
Write-Host -NoNewline "`r$Statustext $progressbar [$($Current.ToString("#,###").PadLeft($Total.ToString("#,###").Length)) / $($Total.ToString("#,###"))] ($($( ($Current / $Total) * 100).ToString("##0.00").PadLeft(6)) %) $CurStatusText"
# There might be old Text behing the current Currsor, so let's write some blanks to the Position of $XOrg
[int]$XNow = $host.UI.RawUI.CursorPosition.X
for ([int]$i = $XNow; $i -lt $XOrg; $i++) {
Write-Host -NoNewline " "
}
# Just for optical reasons: Go back to the last Position of current Line
for ([int]$i = $XNow; $i -lt $XOrg; $i++) {
Write-Host -NoNewline "`b"
}
}
Use the function like this:
For ([int]$i=0; $i -le 8192; $i++) {
Write-Status -Current $i -Total 8192 -Statustext "Running a long Task" -CurStatusText "Working on Position $i"
}
The result will be a running progressbar that will look like this (in a single line):
Running a long Task ██████████████████░░░░░░░░░░░░░░░░░ [4.242 /
8.192] ( 51,78 %) Working on Position 4242
Hope this will help someone else
You can use the .NET console class to do exactly what you want where you want it.
Works in console windows only and not the ISE.
cls
[Console]::SetCursorPosition(40,5)
[Console]::Write('Value of $i = ')
[Console]::SetCursorPosition(40,7)
[Console]::Write('Value of $j = ')
For ($i = 1; $i -lt 11; $i++)
{
[Console]::SetCursorPosition(57,5)
[Console]::Write($i)
for ($j = 1; $j -lt 11; $j++)
{
[Console]::SetCursorPosition(57,7)
[Console]::Write("$j ")
Start-Sleep -Milliseconds 200
}
Start-Sleep -Milliseconds 200
}
[Console]::SetCursorPosition(40,5)
[Console]::Write(" `n")
[Console]::SetCursorPosition(40,7)
[Console]::Write(" `n")
[Console]::SetCursorPosition(0,0)
If the goal is strictly to overwrite powershell console prompt line (the current line with the cursor) then all the answers here work only to an extent, and in some ways doing more than is desired.
Raf's and Craig's answers that use the Clear-Host cmdlet (cls) in their first line, like Dullson noted, are doing too much. Blanking the entire screen assumes the things cleared are no longer important for viewing which may not be true. Sometimes these are necessary to make sense of the current line.
Raf's Write-Progress solution is a powerful cmdlet but seems like an overkill for just overwriting the current line.
Raf's Write-Host proposal, Matt's submission and Dullson's tweak are all good where only one character position at a definite screen position needs updating or where the succeeding line text is longer in length than the current. If not, the succeeding line text would only overwrite the current line to the extent of its length leaving those parts of the succeeded line whose length position is longer than the new to remain in view together with the new line.
For example, if the previous value was 10 and the new value is 9 what would be shown is 90. The 9 just overwrites the portion of the preceding value that is equal to its length - 1. So the solutions work well for increments but not so well for decrements where length of value reduces compared to previous.
The following block shows how to guarantee total (visual) overwrite of the current line text with a new one.
$LongString = "This string is long"
$ShortString = "This is short"
#Simulate typing a string on the console line
$L = 1
While ($L -le $LongString.Length)
{
$Sub = $LongString.Substring(0,$L)
Write-Host "`r$Sub" -NoNewline
$L++
# This sleep is just to simulate manual typing delay
Start-Sleep -Milliseconds 20
}
# Now blank out the entire line with the space character " "
# The quantity of spaces should be equal to the length of the current text
# Which in this case is contained in $Sub.Length
$Blank = " "
For($L = 1; $L -le $Sub.Length; $L++)
{
$Blank = $Blank + " "
}
Write-Host "`r$Blank" -NoNewline
# Overwrite the blank console line with the new string
$L = 1
While ($L -le $ShortString.Length)
{
$Sub = $ShortString.Substring(0,$L)
Write-Host "`r$Sub" -NoNewline
$L++
# This sleep is just to simulate delay in manual typing
Start-Sleep -Milliseconds 20
}
# The following is not required if you want the Powershell prompt
# to resume to the next line and not overwrite current console line.
# It is only required if you want the Powershell prompt to return
# to the current console line.
# You therefore blank out the entire line with spaces again.
# Otherwise prompt text might be written into just the left part of the last
# console line text instead of over its entirety.
For($L = 1; $L -le $Sub.Length; $L++)
{
$Blank = $Blank + " "
}
Write-Host "`r$Blank" -NoNewline
Write-Host "`r" -NoNewline
This one I got from a blog post by Thomas Rayner. He uses ANSI Escape Sequences to save the cursor position [s and update the cursor position [u
$E=[char]27
Then save the current cursor position using the save escape sequence:
"${E}[s"
Usage: Use the update sequence ${E}[u to tell PS where to start the string:
1..10 | %{"${E}[uThere are $_ s remaining"; Start-Sleep -Seconds 1}
Does not work in the ISE however.
I know links get stale but it is here today.
Try
for ($i=1;$i -le 100;$i++){Write-Host -NoNewline "`r" $i;sleep 1}
https://241931348f64b1d1.wordpress.com/2017/08/23/how-to-write-on-the-same-line-with-write-output/
This method worked for me to write output value in a loop until its status changed to "Succeeded". Ensure you set the cursor up by required number of lines and it overwrites the same line
while($val -ne 1)
{
if($taskstates.Tasks.state[0] -eq "Succeeded" -and $taskstates.Tasks.state[1] -eq "Succeeded" -and $taskstates.Tasks.state[2] -eq "Succeeded" -and $taskstates.Tasks.state[3] -eq "Succeeded")
{
$val = 1
}
#Clear-Host
$taskstates.Tasks.StartTime[0].ToString() +" "+ $taskstates.Tasks.name[0] +" is "+ $taskstates.Tasks.state[0]
$taskstates.Tasks.StartTime[1].ToString() +" "+ $taskstates.Tasks.name[1] +" is "+ $taskstates.Tasks.state[1]
$taskstates.Tasks.StartTime[2].ToString() +" "+ $taskstates.Tasks.name[2] +" is "+ $taskstates.Tasks.state[2]
$taskstates.Tasks.StartTime[3].ToString() +" "+ $taskstates.Tasks.name[3] +" is "+ $taskstates.Tasks.state[3]
$taskstates = Get-ASRJob -Name $failoverjob.Name
"ASR VMs build is in Progress"
Start-Sleep 5
[console]::setcursorposition($([console]::Cursorleft ),$([console]::CursorTop - 4))
}
I'm late to the party. Here's a proof of concept I recently discovered and adapted for my purposes. This example overwrites the line.
$count = 1
# Used for calculating the max number length for padding trailing spaces
$totalCount = 100
#Get current cursor position
$curCursorPos = New-Object System.Management.Automation.Host.Coordinates
$curCursorPos.X = $host.ui.rawui.CursorPosition.X
$curCursorPos.Y = $host.ui.rawui.CursorPosition.Y
# Counter code
While ($count -le 100) {
# Keep cursor in the same position on the same line
$host.ui.rawui.CursorPosition = $curCursorPos
# Display with padded trailing spaces to overwrite any extra digits
$pad = ($totalCount -as [string]).Length
# Display the counter
Write-Host "$(([string]$count).Padright($pad))" -NoNewline -ForegroundColor Green
# Run through the example quickly
Start-Sleep -Milliseconds 100
#increment $count
$count++
}
You can experiment with Write-Host -NoNewline property, by keeping it or removing it, to see which looks better for you.
I like below code...
$dots = ""
while (!$isTrue) {
if ($dots -eq "...") {
$dots = ""
}
else {
$dots += "."
}
Write-Host -NoNewLine "`rLoading$dots"
Start-Sleep 1
}
You can use $Host.UI.RawUI.WindowSize.Width to find the display width and then use .PadRight to fill up the line with spaces. This avoids having to clear the screen with each loop, the issue of characters persisted from the last loop, having to manipulate cursor position, or having to write a custom function or lots of cumbersome code, e.g.:
# only works in a console window
If ($Host.Name -eq "ConsoleHost")
{
Write-Host 'Starting...'
# find the max line length of the console host
$maxLineLength = $Host.UI.RawUI.WindowSize.Width
# loop a few times
For ($i = 1; $i -le 10; $i++)
{
# for the sake of demonstration, generate a random-length string of letters
$randStringLength = Get-Random -Minimum 1 -Maximum $maxLineLength
$randCharIndex = Get-Random -Minimum 65 -Maximum (65+26) # A = ASCII 65
$randChar = ([char]$randCharIndex)
$myString = [string]$randChar*$randStringLength
# overwrite at the current console line
Write-Host ("`r"+$myString.PadRight($maxLineLength," ")) -NoNewline
# pause briefly before going again
Start-Sleep -Milliseconds 200
}
Write-Host 'Done.'
}
Another option in PowerShell 7.2+ is to use the minimal Write-Progress view $PSStyle.Progress.View = Minimal:
# only works in a console window
If ($Host.Name -eq "ConsoleHost")
{
# loop a few times
For ($i = 1; $i -le 10; $i++)
{
# for the sake of demonstration, generate a random-length string of letters
$randStringLength = Get-Random -Minimum 1 -Maximum 500
$randCharIndex = Get-Random -Minimum 65 -Maximum (65+26) # A = ASCII 65
$randChar = ([char]$randCharIndex)
$myString = [string]$randChar*$randStringLength
# overwrite at the current console line
Write-Progress -Activity $i -Status $myString
# pause briefly before going again
Start-Sleep -Milliseconds 200
}
}
Alot of good suggestions here...
I use the WindowTitle bar for monitoring the status of my scripts, indicate where I am within my code, & the current progress.
For($t = 0; $t -le 100; $t++) {
$Host.UI.RawUI.WindowTitle = "Progress - $t% complete"
Start-Sleep -Milliseconds 10
}
I'll even insert updated "position" info within my code, to indicate where I'm at within my code:
$Host.UI.RawUI.WindowTitle = "Querying index..."
$Host.UI.RawUI.WindowTitle = "Updating search field..."
$Host.UI.RawUI.WindowTitle = "Conducting Robocopy..."
and of course when it's completed:
$Host.UI.RawUI.WindowTitle = "Script completed."