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

PowerShell循环中Write-Progress完全不显示问题求助

PowerShell中Write-Progress进度条不显示问题排查

问题描述

我正在开发一款学生活动票务预约机器人脚本,原本通过循环等待票务开售,Write-Progress应实时提示剩余开售时间。此前功能正常,但未修改循环代码的情况下,Write-Progress完全不显示,且无任何报错。

尝试过的脚本片段

初始While循环写法

While ($currentDate -lt $purchaseTime){
  $currentDate = Get-Date
  $waitTime = (New-TimeSpan -End $purchaseTime).TotalSeconds
  Write-Progress -Activity "Waiting until sales start" -SecondsRemaining $waitTime
  Start-Sleep -Milliseconds 10
  If ($currentDate -ge $purchaseTime){continue}
} 

改为Do-Until循环写法

Do {
  $currentDate = Get-Date
  $waitTime = (New-TimeSpan -End $purchaseTime).TotalSeconds
  Write-Progress -Activity "Waiting until sales start" -SecondsRemaining $waitTime
  Start-Sleep -Milliseconds 201
} until ($currentDate -gt $purchaseTime)

补充信息

编辑1:目标时间获取方式

$purchaseTime通过GET请求返回的JSON对象获取,具体代码与值如下:

$purchaseTime = $jsonObject.model.product.dateSalesFrom
# 对应字符串值:"2022-11-25T11:00:00+02:00"

日期格式此前一直正常,尝试了Mathias建议的代码后问题依旧。使用的PowerShell版本为5.1,是否需要提供完整脚本?

编辑2:采用新写法后仍无效

已改用Santiago建议的代码,但进度条仍不显示。这段代码单独运行正常,怀疑是JSON日期格式的问题?当前循环代码如下:

$nowDate    = Get-Date
$targetDate = Get-Date $jsonObject.model.product.dateSalesFrom
$timeSpan   = $targetDate - $nowDate
$stopWatch  = [System.Diagnostics.Stopwatch]::StartNew()

Do {
    $progess = @{
        Activity         = 'Waiting until sales start'
        SecondsRemaining = ($timeSpan - $stopWatch.Elapsed).TotalSeconds
    }
    Write-Progress @progess

    Start-Sleep -Milliseconds 200
}
until($stopWatch.Elapsed -ge $timeSpan)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:50:44