使用超时调用另一个Powershell脚本

时间:2014-09-25 07:26:08

标签: powershell

我有这个功能:

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"
    }
}

当我打电话给我时,我得到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.

但是,行:

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

本身工作正常。

如何成功调用$ code变量中的powershell脚本?

1 个答案:

答案 0 :(得分:1)

在scriptblock内部定义的变量和函数在scriptblock中不可用。因此,脚本块中的$script:getHDriveSizePath$usersDirectory都是$null,因此您实际上是在尝试运行语句powershell.exe -Path,这会产生您观察到的错误。您需要将变量作为参数传递到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'
  }
}