adding a timeout to batch/powershell

前端 未结 5 1364
面向向阳花
面向向阳花 2020-12-10 14:05
$fullnamexp = ((net user $winxp /domain | Select-String \"Full Name\") -replace \"Full Name\",\"\").Trim();

If $winxp cannot be found,

5条回答
  •  情话喂你
    2020-12-10 14:38

    While @mjolinor may have indeed provided you an alternative approach, here is a direct answer to your general question: how do you force a timeout in PowerShell?

    Wrap whatever you wish to time-limit in a script block, run that as a job, then use the Wait-Job cmdlet to time-limit the operation. Wait-Job will return either at the end of the timeout period or when the script block completes, whichever occurs first. After Wait-Job returns, you can examine the job state ($j.state) to determine whether it was interrupted or not, if it matters to you.

    $timeoutSeconds = 5 # set your timeout value here
    $j = Start-Job -ScriptBlock {
        # your commands here, e.g.
        Get-Process
        }
    "job id = " + $j.id # report the job id as a diagnostic only
    Wait-Job $j -Timeout $timeoutSeconds | out-null
    if ($j.State -eq "Completed") { "done!" }
    elseif ($j.State -eq "Running") { "interrupted" }
    else { "???" }
    Remove-Job -force $j #cleanup
    

    2014.01.18 Update

    Here is a bit more streamlining approach that also includes the practical step of getting information out of the script block with Receive-Job, assuming what you want is generated on stdout:

    $timeoutSeconds = 3
    $code = {
        # your commands here, e.g.
        Get-ChildItem *.cs | select name
    }
    $j = Start-Job -ScriptBlock $code
    if (Wait-Job $j -Timeout $timeoutSeconds) { Receive-Job $j }
    Remove-Job -force $j
    

提交回复
热议问题