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

}
BenH
  • 9,766
  • 1
  • 22
  • 35
user2233677
  • 199
  • 1
  • 8
  • 2
    Take a look at [`Get-Help about_Remote_Variables`](https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_remote_variables) and [`Get-Help about_Scopes`](https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_scopes). You will also find [this StackOverflow question](http://stackoverflow.com/questions/24996816/powershell-remoting-using-variable-scope) useful. – Jeff Zeitlin Mar 28 '17 at 17:40

1 Answers1

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 }
Frode F.
  • 52,376
  • 9
  • 98
  • 114
  • The first one did work. Looks like my powershell is not v 3 so the second one returned an error. Thank you so much! – user2233677 Mar 28 '17 at 18:14