0

I have this function:

function getHDriveSize($usersHomeDirectory)
{
    $timeOutSeconds = 600
    $code = 
    {
        $hDriveSize = powershell.exe $script:getHDriveSizePath - path $usersDirectory
        return $hDriveSize
    }

    $job = Start-Job -ScriptBlock $code

    if (Wait-Job $job -Timeout $timeOutSeconds)
    {
        $receivedJob = Receive-Job $job
        return $receivedJob
    }
    else
    {
        return "Timed Out"
    }
}

When I call it, I get a CommandNotFoundException:

-path : The term '-path' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

However, the line:

$hDriveSize = powershell.exe $script:getHDriveSizePath - path $usersDirectory

by itself works fine.

How can I call the powershell script within the $code variable successfully?

2
  • 1
    First of all, - path cannot work. Second, it appears that $script:getHDriveSizePath seems to not exist, so PowerShell just gets an empty string there and tries executing -path. Third, your function name is way off and should probably be something like Get-HDriveSize instead. Commented Sep 25, 2014 at 7:40
  • @Joey That's probably just a typo, because the output would be different otherwise. Commented Sep 25, 2014 at 8:38

1 Answer 1

1

Variables and functions defined outside the scriptblock are not available inside the scriptblock. Because of this, both $script:getHDriveSizePath and $usersDirectory inside the scriptblock are $null, so that you're actually trying to run the statement powershell.exe -Path, which produces the error you observed. You need to pass variables as parameters into the scriptblock:

function getHDriveSize($usersHomeDirectory) {
  $timeOutSeconds = 600

  $code = {
    & powershell.exe $args[0] -Path $args[1]
  }

  $job = Start-Job -ScriptBlock $code -ArgumentList $script:getHDriveSizePath, $usersHomeDirectory

  if (Wait-Job $job -Timeout $timeOutSeconds) {
    Receive-Job $job
  } else {
    'Timed Out'
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.