0

The function below is meant to implement blocked sleep in PowerShell It gets the following error executing Start-Sleep cmdlet:

"Cannot validate argument on parameter 'Seconds'. The argument is null, empty, or an element of the argument collection contains a null value"

The echo prints the correct argument value, but the argument is not passed to the cmdlet. I tried a local variable with the same result. Tried to cast it to string or integer - no avail. The only way it works if the number is hard coded

function BlockedSleep($numSecs)
{
    echo "Sleeping  $($numSecs) seconds"    
    $job = Start-Job {Start-Sleep -s $numSecs }
    Wait-Job $job >$null #this supresses job output to console
    Receive-Job $job

}
1

1 Answer 1

0

The job is executed in another thread that does not have access to your script's parameter. You can either include the variable as a argument to the scriptblock:

$job = Start-Job {param($secs) Start-Sleep -Seconds $secs } -ArgumentList $numSecs

Or you can use the using-variable scope (PS 3.0 +):

$job = Start-Job {Start-Sleep -Seconds $using:numSecs }
Sign up to request clarification or add additional context in comments.

1 Comment

The first one did work. Looks like my powershell is not v 3 so the second one returned an error. Thank you so much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.