Assigning a timeout to invoke-command RRS feed

  • Question

  • My script looks like:

    $my_return_code = invoke-Command -Session $my_session -ScriptBlock {
            Get-ChildItem c:\ *.* -Recurse | select name > c:\myfolder\file1.txt
            } -Args $my_arg1, $my_arg2

    The scriptblock takes usually 300 seconds to complete.

    I need to assign a timeout so that it stops after 30 seconds even if file1.txt is not complete.

    How can I assign a timeout?



    Tuesday, July 11, 2017 11:09 AM

All replies

  • Hi Mario,

    you can do that by executing the command as a job and then manually do the timeout.
    Here's an example implementation for that:

    $job = Invoke-Command -Session $s -ScriptBlock { dir C:\ -Recurse } -AsJob -JobName foo
    $int = 0
    while (($job.State -like "Running") -and ($int -lt 3))
    Start-Sleep -Seconds 1
    if ($Job.State -like "Running") { $job | Stop-Job }
    $job | Receive-Job
    $job | Remove-Job


    PS: It's Receive-Job that is returning the output, in case you want to store and reuse it.

    There's no place like

    Tuesday, July 11, 2017 12:14 PM
  • $so = New-PSSessionOption -OpenTimeout 60 -CancelTimeout 60 -OpenTimeOut 60

    help New-PSSessionOption  -full


    Tuesday, July 11, 2017 1:28 PM
  • $so = New-PSSessionOption -OpenTimeout 60 -CancelTimeout 60 -OpenTimeOut 60

    help New-PSSessionOption  -full


    You have -OpenTimeout twice...did you mean for one of them to be OperationTimeout?

    If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful. (99,108,97,121,109,97,110,50,64,110,121,99,97,112,46,114,114,46,99,111,109|%{[char]$_})-join''

    • Edited by clayman2 Tuesday, July 11, 2017 1:42 PM typo
    Tuesday, July 11, 2017 1:41 PM
  • That is to make the timeout twice as accurate.


    Tuesday, July 11, 2017 8:18 PM
  • Hi Mario,

    Just checking in to see if the information provided was helpful.

    Please let us know if you would like further assistance.

    Best Regards,


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    Monday, August 21, 2017 8:39 AM
  • this made me laugh. Thanks!
    Thursday, October 11, 2018 7:25 PM