0

I am writing below PS code to run my application.

$ReturnVar = Start-Process $WExe $IFile -NoNewWindow -Wait
Write-Host "Success"

After ran my application $WExe $IFile successful, script printing "Success".

I have a one challenge here. If my application get stuck and laying down in background, PS code also laying down in background, since I am giving -NoNewWindow -Wait.

So if my application running time crossing over 30 minutes I want to display/print "Application got stuck in background".

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Er Reddy
  • 29
  • 1
  • 9
  • Possible duplicate of [Powershell Start Process, Wait with Timeout, Kill and Get Exit Code](https://stackoverflow.com/questions/36933527/powershell-start-process-wait-with-timeout-kill-and-get-exit-code) – henrycarteruk Oct 10 '17 at 10:34

1 Answers1

1

Use Background Jobs.

#Create a ScriptBlock
$ReturnVarBlock = {
param(
    [Parameter(Mandatory=$true,
                   Position=0)]
    $WExe,
    [Parameter(Mandatory=$true,
                   Position=1)]
    $IFile
)
    Start-Process $WExe $IFile -NoNewWindow -Wait
}

#Trigger a background Job
Start-Job -Name MyJob -ScriptBlock $ReturnVarBlock -ArgumentList $WExe, $IFIle

#Waiting a max of 30 mins = 1800 seconds after which the wait times out.
Wait-Job -Name MyJob -Timeout 1800


$JobState = (Get-Job -Name MyJob).State
if ($JobState -eq "Completed")
{
    Write-Host "Success"
}
elseif ($JobState -eq "Failed")
{
    Write-Host "Job Failed"
}
else
{
    Write-Host "Job is stuck"
    #Uncomment below line to kill the Job
    #Remove-Job -Name MyJob -Force
}
Sid
  • 2,586
  • 1
  • 11
  • 22
  • Thanks for your reply. It looks like we are waiting for 30 minutes instead of counting `Start-Process $WExe $IFile -NoNewWindow -Wait` execution time. here if application execution completes in 1-2 minutes,but PS will wait for 30 minutes. is there another way to get this done. – Er Reddy Oct 10 '17 at 11:09
  • No it wont wait 30 mins if it finishes early. Did you test this out? – Sid Oct 10 '17 at 11:44
  • Yes, I have tested. it is waiting for 30 minutes even if `Start-Process $WExe $IFile -NoNewWindow -Wait` execution is done. – Er Reddy Oct 10 '17 at 12:10