我有一个计数器脚本,需要两个参数:
1)在计数器开始前等待的秒数。
2)以秒为单位的计数器持续时间。
例如,如果我输入3,10 我想在3秒后计时器将从10倒数到0,并每秒将其写入输出。
这是我的剧本:
$timeBeforeStart = $args[0]
$waitSeconds = $args[1]
$startTime = get-date
$endTime = $startTime.addSeconds($waitSeconds)
$timeSpan = new-timespan $startTime $endTime
start-sleep -s $timeBeforeStart
while ($timeSpan -gt 0)
{
$timeSpan = new-timespan $(get-date) $endTime
write-host $([string]::Format("`rTime Remaining: {0:d2}:{1:d2}:{2:d2}",
$timeSpan.hours, $timeSpan.minutes, $timeSpan.seconds))
sleep 1
}
不幸的是它不起作用,睡眠似乎与计数器同时工作而不是延迟计数器。
PS C:\> c:\555.ps1 3 10
Time Remaining: 00:00:07
Time Remaining: 00:00:05
Time Remaining: 00:00:04
Time Remaining: 00:00:03
Time Remaining: 00:00:02
Time Remaining: 00:00:01
Time Remaining: 00:00:00
Time Remaining: 00:00:00
我也尝试过 start-sleep -s ,结果也一样。
顺便问一下,睡眠与“开始睡眠-s”有什么区别?答案 0 :(得分:2)
睡眠和“开始睡眠-s”之间有什么区别?
没有区别,sleep
只是Start-Sleep
的别名。
不幸的是它不起作用,睡眠似乎与计数器同时工作而不是延迟计数器。
您可能希望在计数器开始之前将睡眠置于第一个$timeSpan
:
start-sleep -s $timeBeforeStart
$startTime = get-date
$endTime = $startTime.addSeconds($waitSeconds)
$timeSpan = new-timespan $startTime $endTime
while ($timeSpan -gt 0)
{
# ...
}
答案 1 :(得分:2)
尝试这种方式:
$timeBeforeStart = 3
$waitSeconds = 10
Start-Sleep -Seconds $timeBeforeStart
$waitSeconds..0 | Foreach-Object {
Write-Host "Time Remaining: $_"
Start-Sleep -Seconds 1
}
Time Remaining: 10
Time Remaining: 9
Time Remaining: 8
Time Remaining: 7
Time Remaining: 6
Time Remaining: 5
Time Remaining: 4
Time Remaining: 3
Time Remaining: 2
Time Remaining: 1
Time Remaining: 0
答案 2 :(得分:1)
尝试这种方式:
$timeBeforeStart = 0
$waitSeconds = 60
Start-Sleep -Seconds $timeBeforeStart
$waitSeconds..0 | Foreach-Object {
Write-Host "`r Time Remaining: $_ " -NoNewline -foregroundcolor green
Start-Sleep -Seconds 1
}
答案 3 :(得分:0)
这也是做同样的事情:
$timeBeforeStart = 3
$waitSeconds = 10
Start-Sleep -Seconds $timeBeforeStart
$endTime = (get-date).addSeconds($waitSeconds)
while ( (get-date) -lt $endTime )
{
Write-Host "Time Remaining: $("{0}" -f ([int](new-timespan $(get-date) $endTime).totalseconds))"
Start-Sleep -Seconds 1
}