Powershell: Update current output line

后端 未结 2 1710
鱼传尺愫
鱼传尺愫 2021-02-20 16:20

is there a way to update the current line of the command output in powershell?

i know how to write to the same line:

Write-Host \"hello \" -NoNewLine

2条回答
  •  有刺的猬
    2021-02-20 17:04

    The solution is to use carriage return while writing to the host, as noted by others. Make sure to use the NoNewLine flag whith write-host or it will not work.

    Carriage Return is acheived by using: `r

    Here's a small example illustrating this answer:

    $up = $true
    $finish = $false
    $timeout = 50
    Write-Host "Updating" -NoNewline
    do {
        for ($i=0;$i -le 100;$i++){
            if ($i -eq 100){$up = !$up}
            if ($up){
                $str = ""
                $x=99-$i
                for($z=0;$z -le $i;$z++){$str+="."}
                for($y=0;$y -le $x;$y++){$str+=" "}
                Write-host "`rUpdating$str" -NoNewline
                Start-Sleep -Milliseconds $timeout
            }else{
                $str = ""
                $x=99-$i
                for($y=0;$y -le $x;$y++){$str+="."}
                for($z=0;$z -le $i;$z++){$str+=" "}
                Write-host "`rUpdating$str" -NoNewline
                Start-Sleep -Milliseconds $timeout
            }
        }
        if ($timeout -le 0){$finish = $true}
        $timeout-=10
    } until ($finish)
    $str = ""
    for ($i=0;$i -le 93;$i++){$str+=" "}
    Write-Host "`rUpdate Complete!$str"
    Read-Host "Press [ENTER] to close this Window"
    

提交回复
热议问题