PowerShell:Console和SetCursorPosition中的角色动画变得疯狂

Far*_*eed 1 msbuild console powershell animation visual-studio-2012

专家,我正在使用msbuild构建一长串Visual Studio项目.在隐藏msbuild输出时,在msbuild完成其工作时会显示基于某些字符的状态和动画.这里我的脚本使用msbuild构建并显示等待动画(你肯定会喜欢这个......):

$anim=@("|","/","-","\","|") # Animation sequence characters
$ReturnCode = @{}
$BuildStatus="Building $(ProjectName)" 

$CursorTop=[Console]::CursorTop #// Cursor position on Y axis
$CursorLeft=$BuildStatus.Length #// Cursor position on X axis 
Write-Host $BuildStatus -ForegroundColor Cyan

#// starting the MsBuild job in background.

$MsbJob = [PowerShell]::Create().AddScript(
{
  param($MsbArgs, $Result)
  & msbuild $MsbArgs | Out-Null
  $Result.Value = $LASTEXITCODE
}
).AddArgument($MsbArgs).AddArgument($ReturnCode)

$async = $MsbJob.BeginInvoke() #// start executing the job.

#// While above script block is doing its job in background, display status and animation in console window.

while (!$async.IsCompleted)
{
    foreach ($item in $anim) #// looping on array containing characters to form animation
    {

       [Console]::SetCursorPosition($CursorLeft + 5,$CursorTop) #//setting position for cursor
       Write-Host $item -ForegroundColor Yellow 
       Start-Sleep -m 50
    }
}

$MsbJob.EndInvoke($async)
Run Code Online (Sandbox Code Playgroud)

大部分时间,它按预期工作,即显示如下状态:

构建MyProject(动画字符)..

但突然间,它变成了这样:在此输入图像描述

只有发现的解决方案:我能够纠正这是为了将控制台的屏幕缓冲区大小(控制台属性 - >布局:屏幕缓冲区大小)增加到1024.此外,我还增加了窗口大小以填写显示器,它没有不要那样打破.

我对Screen Buffer的评估是否正确?还是别的什么都搞砸了?如果是,我是否必须实际增加屏幕缓冲区大小,即从我的.psm1脚本中增加.?

任何帮助将非常感激.

Ans*_*ers 5

默认情况下Write-Host,在打印的字符串后面添加换行符.而不是重新定位光标尝试打印输出而不使用换行符,因此您可以使用backspace(`b)来擦除之前打印的字符:

while (!$async.IsCompleted) {
  $anim | % {
    Write-Host "`b$_" -NoNewline -ForegroundColor Yellow 
    Start-Sleep -m 50
  }
}
Run Code Online (Sandbox Code Playgroud)