Using invoke-command with a timeout

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Will Anderson Will Anderson 2 weeks, 3 days ago.

  • Author
    Posts
  • #74662
    Profile photo of marius
    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
    Profile photo of Will Anderson
    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
    

You must be logged in to reply to this topic.