简体   繁体   English

PowerShell - 如何强制超时调用命令

[英]PowerShell - How to force timeout Invoke-Command

I would like to force-terminate/timeout a PowerShell Invoke-Command remote session after 20 minutes regardless of whether it's busy or idle.我想在 20 分钟后强制终止/超时 PowerShell 调用命令远程 session,无论它是忙还是闲。

How do I achieve this?我如何实现这一目标? Thanks.谢谢。

Something like:就像是:

$job = Start-Job -ScriptBlock { <# Invoke-Command #> }
$job | Wait-Job -Timeout ( 20 * 60 ) | Remove-Job
PS> invoke_command_responsive -Machine pv3040 -Cmd "get-location"

function invoke_command_responsive {
    param(
        [string]$Machine,
        [string]$Cmd
    )
    
    $start_time  = Get-Date
    $start_dir   = better_resolve_path(".")
    $watchdog    = 8 #seconds
    
    [ScriptBlock]$sb = [ScriptBlock]::Create($opt_cmd)              

    $j = Start-Job -ScriptBlock {
        set-location $using:start_dir | out-null
        [ScriptBlock]$sb = [ScriptBlock]::Create($using:cmd)              
        invoke-command -Computer $using:Machine -ScriptBlock:$sb | out-host
    }

    # Wait for Job to Complete or TIMEOUT!
    while($true) {
        if ($j.HasMoreData) {
            Receive-Job $j
            Start-Sleep -Milliseconds 50
        }
        $current = Get-Date
        $time_span = $current - $start_time
        if ($time_span.TotalSeconds -gt $watchdog) {
            write-host "TIMEOUT!"
            Stop-Job $j
            break
        }
        if (-not $j.HasMoreData -and $j.State -ne 'Running') {
            write-host "Finished"
            break
        }
    }
    Remove-Job $j   
}

function better_resolve_path {
    param([string]$path)
    $pathfix = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($path)
    return $pathfix
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM