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
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!
Ikkxeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2