Using invoke-command with a timeout

This topic contains 5 replies, has 4 voices, and was last updated by  js 1 month, 3 weeks ago.

  • Author
    Posts
  • #74662

    marius
    Participant

    I use invoke-command to execute a scriptblock on a remote host.
    My code looks like:

    $my_remote_command = invoke-Command -Session $my_session -ScriptBlock {
    #
    Get-ChildItem c:\ *.* -Recurse | select name > c:\myfolder\myfile.txt
    #
    } 
    

    I need to stop the script block after 30 second, even if myfile.txt is not yet complete.
    How can I set a timeout?
    Regards
    marius

  • #74666

    Will Anderson
    Keymaster

    You could kick it as a job.

    $Job = Start-Job -ScriptBlock {
    
        Invoke-Command -ComputerName localhost -ScriptBlock {
        #
            Get-ChildItem c:\scripts\*.* -Recurse | select name | Out-File 'C:\Scripts\myfile.txt'
        #
        } 
    
    
    }
    
    $Job | Wait-Job -Timeout 10
    $Job | Stop-Job
    
    • #77980

      js
      Participant

      Is there a way to make resolve-dnsname timeout in 1 second? stop-job (or remove-job -force) takes about 4 seconds.

      $job = start-job -scriptblock { Resolve-DnsName 1.1.1.1 }
      $job | wait-job -timeout 1
      measure-command { $job | stop-job }
      
      Days              : 0
      Hours             : 0
      Minutes           : 0
      Seconds           : 4
      Milliseconds      : 148
      Ticks             : 41484183
      TotalDays         : 4.80141006944444E-05
      TotalHours        : 0.00115233841666667
      TotalMinutes      : 0.069140305
      TotalSeconds      : 4.1484183
      TotalMilliseconds : 4148.4183
      
  • #77988

    Curtis Smith
    Participant

    You can try using the -quicktimeout Parameter of the Resolve-DNSName cmdlet. It does not let you specify a timeout value, but it's quicker than the default.

    • #78016

      js
      Participant

      -quicktimeout has no effect in this case. Just try any ip without a hostname.

      I think if the first post here isn't updated, it doesn't appear on the main page.

    • #78022

      js
      Participant

      Oh well. In this case, -dnsonly fixes it.

You must be logged in to reply to this topic.