Search code examples
powershellpowershell-4.0

Wait for process to end


I have a powershell script that will automatically print all .pdf files in a folder with Foxit. I have it set to wait until Foxit has exited until the script continues. Every once in a while, the script will pause and wait even though Foxit has already exited. Is there a way to make it time out after a certain amount of time?

Here is the code I have:

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

I've tried the recommendations here and they don't seem to work. For example if I do:

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

I get:

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

Any help would be greatly appreciated.


Solution

  • I think I figured it out. If I start it with Invoke-WmiMethod I can get the process ID and wait for it, then ask it to time out.

    $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
    

    This seems to work pretty consistantly.