Veverke
Veverke

Reputation: 11368

Powershell Start-Sleep behaves differently with a variable than when using a hardcoded value

I am having trouble in deciphering what is going on with the powershell excerpt below. Running it using a hardcoded value instead of $timeoutInSecs variable - works as expected (see output at the bottom). However, if I try to set Start-Sleep using a parameter carrying the very same value - the script always complete stating the created job has already completed.

All I could think of is maybe because -Seconds requires a double parameter - but that does not make sense - it is implicitly converted into int (and it works with the hardcoded value, so this does not seem to have anything to do with it).

Other than that, I am clueless. Any help would be appreciated.

This looked related, but OP complains about a slightly different issue.

param(
    [int] $timeoutInSecs
)
Write-Host "timeoutInSecs: [$timeoutInSecs]"
#$job = Start-Job -ScriptBlock { Start-Sleep -Seconds $timeoutInSecs }
$job = Start-Job -ScriptBlock { Start-Sleep -Seconds 5 }
$iteration = 1
while($job.State -ne "Completed")
{
    Write-Host "Iteration: [$iteration] job state: [$($job.State)]"
    $iteration++
    Start-Sleep -s 1
}

Write-Host "job state: [$($job.State)]"
Remove-Job $job

Output when using Start-Sleep with hardcoded value of 5: enter image description here

Using Start-Sleep as in the commented line, gives as output: enter image description here

Upvotes: 0

Views: 41

Answers (0)

Related Questions