0

我有一个 powershell 脚本,它会自动打印 Foxit 文件夹中的所有 .pdf 文件。我将它设置为等到 Foxit 退出,直到脚本继续。每隔一段时间,即使 Foxit 已经退出,脚本也会暂停并等待。有没有办法让它在一定时间后超时?

这是我的代码:

Start-Process $foxit -ArgumentList $argument -Wait
Move-Item $filePath $printed[$location]
Add-Content "$printLogDir\$logFileName" $logEntry

我已经尝试过这里的建议,但它们似乎不起作用。例如,如果我这样做:

$proc = Start-Process $foxit -ArgumentList $argument
$proc.WaitForExit()
Move-Item $filePath $printed[$location]
Add-Content "$printLogDir\$logFileName" $logEntry

我得到:

You cannot call a method on a null-valued expression.

任何帮助将不胜感激。

4

4 回答 4

1

我想我想通了。如果我启动它,Invoke-WmiMethod我可以获得进程 ID 并等待它,然后让它超时。

$proc = Invoke-WmiMethod -Class win32_process -Name create -ArgumentList "$foxit $argument"
Wait-Process -Id $proc.ProcessId -Timeout 120
Move-Item $filePath $printed[$location]
Add-Content "$printLogDir\$logFileName" $logEntry

这似乎非常一致。

于 2013-11-19T17:38:56.900 回答
0

实现超时的一种方法是使用后台作业:

$Job = start-job -ScriptBlock { write-output 'start';Start-Sleep -Seconds 15 }

$timeout = New-TimeSpan -Seconds 10
$timer = [diagnostics.stopwatch]::StartNew()

  While ($timer.Elapsed -le $timeout)
   {
    if ($Job.State -eq 'Completed' )
     {
      Receive-Job $Job
      Remove-Job  $Job
      Return
     } 
     Start-Sleep -Seconds 1
    } 
      write-warning 'Job timed out.  Stopping job'
      Stop-Job $Job
      Receive-Job $Job
      Remove-Job  $Job
于 2013-11-19T17:33:06.733 回答
0

我遇到了同样的问题,并找到了一个稍微简单的解决方案,它也捕获了子进程的输出。该-PassThru参数是关键,因为它为 cmdlet 启动的每个进程返回一个进程对象。

$proc = Start-Process $foxit -ArgumentList $argument -PassThru
Wait-Process -Id $proc.Id -Timeout 120
Move-Item $filePath $printed[$location]
Add-Content "$printLogDir\$logFileName" $logEntry
于 2015-08-06T22:22:49.337 回答
0

我更喜欢这种风格,以便更好地控制在外部进程运行时要做什么:

$waitTime = 60
$dism = Start-Process "$env:windir\system32\dism.exe" -ArgumentList "/Online /Cleanup-Image /ScanHealth" -PassThru -WindowStyle Hidden
while (!$dism.HasExited -or $waitTime -gt 0) {sleep -Seconds 1; $waitTime--}
"done."

通过检查 HasExited 属性,我可以继续使用我的代码并行执行任何其他任务。

于 2020-08-26T06:53:48.633 回答