You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell中实现自定义进度条并保留完成提示?

PowerShell 自定义持久化进度条实现

要实现位于控制台最后一行、完成后保留“100% Success”的进度条,可以直接通过控制台光标控制来实现,替代会自动消失的Write-Progress。以下是具体实现方案:

基础实现代码

# 模拟任务总步数
$totalSteps = 50
# 进度条显示长度(字符数)
$barLength = 50

# 先输出空行占位,用于后续进度条输出
Write-Host "`n" -NoNewline

foreach ($step in 1..$totalSteps) {
    # 计算进度百分比
    $percent = ($step / $totalSteps) * 100
    # 计算进度条填充部分长度
    $filled = [Math]::Round(($percent / 100) * $barLength)
    # 构建进度条字符串
    $progressBar = "[" + ("#" * $filled) + ("-" * ($barLength - $filled)) + "]"
    # 组合完整进度文本
    $progressText = "Progress: {0:N1}% {1}" -f $percent, $progressBar

    # 将光标定位到进度行的起始位置(覆盖上一次输出)
    [Console]::SetCursorPosition(0, [Console]::CursorTop - 1)
    # 输出进度内容,不换行
    Write-Host $progressText -NoNewline

    # 模拟任务执行耗时
    Start-Sleep -Milliseconds 100
}

# 任务完成后,覆盖进度条输出最终成功信息
[Console]::SetCursorPosition(0, [Console]::CursorTop - 1)
Write-Host "100% Success"

关键逻辑说明

  • 光标控制:通过[Console]::SetCursorPosition将光标定位到上一行起始位置,每次循环覆盖之前的进度内容,确保进度条始终显示在控制台最后一行。
  • 进度可视化:用#表示已完成部分,-表示未完成部分,可根据喜好替换为其他字符(如=、>)。
  • 持久化输出:所有输出直接写入控制台缓冲区,不会像Write-Progress那样在脚本结束或取消时自动清除。

处理脚本取消场景

如果需要在用户按Ctrl+C终止脚本时,保证控制台输入体验正常,可添加try/finally块:

try {
    $totalSteps = 50
    $barLength = 50

    Write-Host "`n" -NoNewline

    foreach ($step in 1..$totalSteps) {
        $percent = ($step / $totalSteps) * 100
        $filled = [Math]::Round(($percent / 100) * $barLength)
        $progressBar = "[" + ("#" * $filled) + ("-" * ($barLength - $filled)) + "]"
        $progressText = "Progress: {0:N1}% {1}" -f $percent, $progressBar

        [Console]::SetCursorPosition(0, [Console]::CursorTop - 1)
        Write-Host $progressText -NoNewline

        Start-Sleep -Milliseconds 100
    }

    [Console]::SetCursorPosition(0, [Console]::CursorTop - 1)
    Write-Host "100% Success"
}
finally {
    # 确保脚本终止时光标移至新行,避免后续输入与进度内容重叠
    Write-Host ""
}

内容的提问来源于stack exchange,提问作者axcro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 14:55:07