强制PowerShell pipline结束

时间:2016-03-31 13:45:55

标签: .net multithreading powershell

我有一个模块应该以异步方式运行8个命令, 每个命令都将查询不同服务的状态。

其中一个服务查询偶尔会超时(默认为60秒)。 我不想等那么久,因为我的模块在较短的时间间隔内重复出现。

我正在使用' WaitAny()'并将超时定义为10000毫秒(10秒)。 当' WaitAny()'超时将生效$ h变量的值为' 258'。 那是我想迫使pipline退出的时候。 我使用了' BeginStop()',但它似乎无法做任何事情。 在我发布了一个' BeginStop()'它将在60秒的剩余时间内停留,并且不会继续。

如何强行使管道结束,然后继续。

$pool = [RunspaceFactory]::CreateRunspacePool(1,8,$sessionstate,$Host)
$pool.ThreadOptions = "ReuseThread"
$pool.ApartmentState = "STA"
$pool.Open()
$res = @()
$i = 0
foreach ($CurrService in $Blocks) {
    $pipeline = [System.Management.Automation.PowerShell]::Create()
    $pipeline.RunspacePool = $pool
    [void]$pipeline.AddScript($ScriptBlock).AddArgument($CurrService.Service).AddArgument($CurrService.Command)
    $pipelines.Add($pipeline)
    $job = $pipeline.BeginInvoke()
    $jobs.Add($job)
    $handles.Add($job.AsyncWaitHandle)
    $i++
}
while ($pipelines.Count -gt 0) {
    $h = [System.Threading.WaitHandle]::WaitAny($handles,10000,$true)
    if ($h -eq 258) {
        $callback = {
            (New-Object System.Threading.ManualResetEvent($false)).Set()
        }
        foreach ($y in $pipelines) {
            # Every pipline that is still open should be terminated immediately 
            $y.BeginStop($callback,$null)
        }
        continue
    }
    $handle = $handles.Item($h)
    $job = $jobs.Item($h)
    $pipeline = $pipelines.Item($h)
    $res += $pipeline.EndInvoke($job)
    $handles.RemoveAt($h)
    $jobs.RemoveAt($h)
    $pipelines.RemoveAt($h)
    $handle.Dispose()
    $pipeline.Dispose()
}
$pool.Close()

1 个答案:

答案 0 :(得分:0)

此脚本检查是否有一些App-pole Stop $ SourcePath是IIS应用程序路径

param (
    [Parameter (Mandatory = $true)]
    $SourcePath

)
$ErrorActionPreference = "Stop"

try {
    write-host  $SourcePath
    $SourcePath=$SourcePath -replace(':','$')
    write-host  $SourcePath
    $LASTEXITCODE =1
    exit $LASTEXITCODE

}Catch{
    $ErrorMessage = $_.Exception.Message
    $FailedItem = $_.Exception.ItemName
    write-verbose "Error: '$ErrorMessage' - on item: '$FailedItem'"  -verbose
    Break
}



#Jenkins Pipeline Catch exception from Powershell 
def ComponentPath =params.ComponentPath
def libName = 'Devops'
def slnPath = "C:/${libName}"
node {

   stage('test'){

  def status =   powershell returnStatus: true, script: "${slnPath}/deploy_scripts/BackUpBeforeDeployM.ps1  -SourcePath ${ComponentPath}"
     if (status == 0) {
        println 'Success!'
    }else
    {

      error("iis check failed")


    }

}
}