Search code examples
powershelltimeoutstart-job

How can I put a timeout on a powershell command?


I tried this code but only file1.txt gets created. File2.txt does not. I'm looking for the built-in way to use timeouts. So not by creating custom loops.

Out-File "file1.txt"                  #this file is created

$Job = Start-Job -ScriptBlock {            
        Out-File "file2.txt"          #this file is not created
}
$Job | Wait-Job -Timeout 5
$Job | Stop-Job

Solution

  • I have finally found the solution. The Start-Job script starts in a default home folder, different from the script location. So it works if I use an absolute path. I like this code much better than custom made loops:

    Start-Job {                
        Out-File "C:\file2.txt"
    } | Wait-Job -Timeout 3