等待等待时间

时间:2017-10-10 09:50:30

标签: powershell

我正在编写PS代码以运行我的应用程序。

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

运行我的应用程序$WExe $IFile成功后,脚本打印"成功"。

我这里有一个挑战。如果我的应用程序卡在背景中,PS代码也会放在后台,因为我给的是-NoNewWindow -Wait

因此,如果我的应用程序运行时间超过30分钟,我想显示/打印"应用程序卡在后台"。

1 个答案:

答案 0 :(得分:1)

使用后台工作。

#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
}