Reputation: 6446
I have a script of counter that expects two parameters:
1) seconds to wait before the counter starts.
2) counter duration in seconds.
For example, if I input 3,10 I would like that after 3 seconds the timer will countdown from 10 to 0 and write it to the output every second.
This is my script:
$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
}
Unfortunately it doesn't work, the sleep seems to work simultaneity with the counter instead of delay the counter.
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
I've also tried start-sleep -s and the results where the same.
by the way, what is the difference between sleep and "start-sleep -s" ?
Upvotes: 1
Views: 6006
Reputation: 21
Try this way:
$timeBeforeStart = 0
$waitSeconds = 60
Start-Sleep -Seconds $timeBeforeStart
$waitSeconds..0 | Foreach-Object {
Write-Host "`r Time Remaining: $_ " -NoNewline -foregroundcolor green
Start-Sleep -Seconds 1
}
Upvotes: 2
Reputation: 1
This also does the same thing:
$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
}
Upvotes: 0
Reputation: 126792
Try this way:
$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
Upvotes: 2
Reputation: 24826
what is the difference between sleep and "start-sleep -s"?
No difference, sleep
is just alias of Start-Sleep
.
Unfortunately it doesn't work, the sleep seems to work simultaneity with the counter instead of delay the counter.
You might want to put the sleep before the counter starts before getting the first $timeSpan
:
start-sleep -s $timeBeforeStart
$startTime = get-date
$endTime = $startTime.addSeconds($waitSeconds)
$timeSpan = new-timespan $startTime $endTime
while ($timeSpan -gt 0)
{
# ...
}
Upvotes: 2