调用另一个带超时的Powershell脚本

调用另一个带超时的Powershell脚本,powershell,Powershell,我有这个功能: function getHDriveSize($usersHomeDirectory) { $timeOutSeconds = 600 $code = { $hDriveSize = powershell.exe $script:getHDriveSizePath - path $usersDirectory return $hDriveSize } $job = Start-Job -ScriptBlo

我有这个功能:

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"
    }
}
当我调用它时,我得到一个
命令notfoundexception

-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脚本?

在scriptblock外定义的变量和函数在scriptblock内不可用。因此,scriptblock中的
$script:getHDriveSizePath
$usersDirectory
都是
$null
,因此您实际上正在尝试运行语句
powershell.exe-Path
,这会产生您观察到的错误。您需要将变量作为参数传递到scriptblock:

函数getHDriveSize($usershomedidirectory){ $timeOutSeconds=600 $code={ &powershell.exe$args[0]-路径$args[1] } $job=Start job-ScriptBlock$code-ArgumentList$script:getHDriveSizePath,$usershomedidirectory if(等待作业$Job-超时$timeOutSeconds){ 接收Job$Job }否则{ “超时” } }
首先,
-path
无法工作。其次,似乎不存在
$script:getHDriveSizePath
,因此PowerShell只在那里获取一个空字符串,并尝试执行
-path
。第三,你的函数名太离谱了,应该是
Get-HDriveSize
之类的名称。@Joey这可能只是一个输入错误,否则输出会有所不同。