如何设置 PowerShell 函数的超时



我有一个脚本,它正在获取呼叫中心许多机器的磁盘空间信息。但是,有时此功能需要很长时间。我需要为该功能创建一个超时,但一直无法做到。我尝试使用开始工作,但老实说,我不完全理解它,所以我没有得到预期的结果。

try {
    $timeoutSeconds = 30
    $code = {
      param($currentPCname, $activeDriveTypes)
// Function which takes computer name as input and outputs the ComputerName,DeviceID, Size, Freespace and DriveType (3 = local)
      function get-FDS { 
        [cmdLetBinding()]
        Param([string]$hostName)
        Get-WmiObject Win32_LogicalDisk -ComputerName $hostName | 
        Where-object {$_.DriveType -in $activeDriveTypes} | 
        select-Object @{Name="ComputerName";Expression={$hostName}}, @{Name="Date";Expression={Get-Date}}, DeviceID, Size, Freespace, DriveType
      } 
      get-FDS($currentPCname) -errorAction stop
    }
    $processTime = measure-command { 
      $j = Start-Job -ScriptBlock $code -Arg $currentPCname, $activeDriveTypes 
      if (Wait-Job $j -Timeout $timeoutSeconds) { $tempData = Receive-Job $j }
      $jobState = $j.state
      Remove-Job -force $j
    }
    if ($jobState -ne 'Completed') {
        $pcTurnedOn = $false
        $errorMessage = "ERROR talking to $currentPCname : Query timed-out"
        $query = "CALL sp_fds_insert_log(" + $currentRunID + ", '" + $errorMessage + "', '" + $scriptName + "');"
        $cmd = new-object mysql.data.mysqlclient.mysqlcommand($query, $conn) 
        $cmd.executenonquery()
    }
} catch {
    $pcTurnedOn = $false
    $errorMessage = "ERROR talking to $currentPCname : $_"
    $query = "CALL sp_fds_insert_log(" + $currentRunID + ", '" + $errorMessage + "', '" + $scriptName + "');"
    $cmd = new-object mysql.data.mysqlclient.mysqlcommand($query, $conn) 
    $cmd.executenonquery() 
}

上面代码的要点是,如果下面的行调用$code段

$processTime = measure-command { 
  $j = Start-Job -ScriptBlock $code -Arg $currentPCname, $activeDriveTypes
  if (Wait-Job $j -Timeout $timeoutSeconds) { $tempData = Receive-Job $j }
  $jobState = $j.state
  Remove-Job -force $j
}

需要 30 多秒,这是$timeoutSeconds,将调用最后一个 IF 语句,如果上面的行由于某种原因不起作用,则将调用 catch 语句,如果它在不到 30 秒内工作,则不会调用任何内容。

如果作业在达到超时之前完成,Wait-Job将返回作业本身 - 如果超过超时,它不会返回任何内容:

$timeout = 2
$job = Start-Job { Start-Sleep -Seconds 3 }
$done = $job |Wait-Job -TimeOut $timeout
if($done){
    # It returned within the timeout 
}
else {
    # Nothing was returned, job timed out
}

相关内容

  • 没有找到相关文章

最新更新