如何为 powershell 命令设置超时?

Fer*_*rro 4 powershell timeout start-job

我尝试了这段代码,但只创建了 file1.txt 。File2.txt 没有。我正在寻找使用超时的内置方法。所以不是通过创建自定义循环。

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
Run Code Online (Sandbox Code Playgroud)

Fer*_*rro 9

我终于找到了解决方案。Start-Job 脚本在默认主文件夹中启动,该文件夹与脚本位置不同。所以如果我使用绝对路径它就有效。与定制循环相比,我更喜欢这段代码:

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

Run Code Online (Sandbox Code Playgroud)