-1

I've set the OperationTimeout to 10 seconds, but when I run a command that sleeps for 20 seconds inside an Invoke-Command block on a remote computer, I don't get an error. Here's the code:

$sessionOptions = New-PSSessionOption -OperationTimeout 10000
$session = New-PSSession -ComputerName "RemoteComputerName" -SessionOption $sessionOptions

try {
    Invoke-Command -Session $session -ScriptBlock {
        Start-Sleep -Seconds 20  
        Get-Date
    }
} catch {
    Write-Error "OperationTimeoutException occurred: $_"
}

Remove-PSSession -Session $session

Could someone explain why there's no OperationTimeoutException error occurring in this scenario?

5
  • 1
    OperationTimeout does not impose a time limit on commands or processes running in a remote session and does not affect other remoting protocols like SSH Commented Jul 16, 2024 at 10:59
  • @user459872 what about OpenTimeout and IdleTimeout? is there a way to impose such limit using New-PSSessionOption? Commented Jul 16, 2024 at 11:04
  • 1
    @user2978216 One option is to dispatch the remote invocation as a job, eg. $remoteJob = Invoke-Command ... -AsJob, then use Wait-Job -Timeout 10 to impose the timeout Commented Jul 16, 2024 at 12:03
  • Yeah I wish there was a timeout option for invoke-command for the initial connection. Commented Jul 16, 2024 at 15:03
  • @user459872 Interesting idea. It sounds like a potential solution, but I'm curious about how it works. If I send an array of 1,000 computers to 'Invoke-Command ... -AsJob,' will all childjobs run simultaneously, or is there some kind of throttling mechanism in place? Commented Jul 17, 2024 at 4:52

1 Answer 1

0

In this case the -OperationTimeout is not directly related to the script block duration. So in this block of code, I have implated a timeout that if the script block exceeds the specified timeout it will throws an exception.

This block of code will solution your problem:

$session = New-PSSession -ComputerName "computername"

$scriptBlock = {
    param ($Timeout)
    
    $startTime = [DateTime]::Now
    $checkInterval = 1
    $elapsedTime = 0

    while ($true) {
        Start-Sleep -Seconds $checkInterval
        $elapsedTime = ([DateTime]::Now - $startTime).TotalSeconds

        if ($elapsedTime * 1000 -ge $Timeout) {
            Write-Host "Script execution exceeded the timeout of $Timeout"
            break
        }
    }
}

Invoke-Command -Session $session -ScriptBlock $scriptBlock -ArgumentList 10000

Remove-PSSession -Session $session

Regards!

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, friend. My guess is that the "if(...)" statement will never be reached until "Start-Sleep" is completed.
ok, check now the edited answer, i think that this is a solution for you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.