从PowerShell

时间:2015-11-13 21:08:58

标签: powershell powershell-v2.0 powershell-v3.0 powershell-v4.0 powershell-ise

如何从称为后台作业的函数中返回返回值?

#Create the Status Background Job 
Start-Job -Name "jobGetStatus" -InitializationScript $InitScript -ScriptBlock {$Status = GetStatus}

#Wait for job result
While (Get-Job -Name "jobGetStatus" | where { $_.State -eq "Running" })
    {Start-Sleep 1}

#Get Status on Timer Tick
$Timer.Add_Tick({Get-Job -Name "jobGetStatus" | Receive-Job -Keep})

在我的例子中,我调用返回数组的函数“GetStatus”。该函数包含在初始化脚本中。

已经尝试过这样的事情:

#Get Status on Timer Tick
$Timer.Add_Tick({$Status = Get-Job -Name "jobGetStatus" | Receive-Job -Keep})

这个案子杀了我......

1 个答案:

答案 0 :(得分:0)

你需要一个计时器吗?在工作完成后获得结果是否合适?

  $event = Register-EngineEvent -SourceIdentifier NewMessage -Action {
      $global:Status = $event.MessageData
  }

  $scriptBlock =  {
    Register-EngineEvent -SourceIdentifier NewMessage -Forward
    # here is logic for status message #
    $statusMessage = @("Your", "status", "array", "here")
    $null = New-Event -SourceIdentifier NewMessage -MessageData $statusMessage

    Unregister-Event -SourceIdentifier NewMessage
  }

  Start-Job -Name "jobGetStatus" -ScriptBlock $scriptBlock | out-null

  While (Get-Job -Name "jobGetStatus" | where { $_.State -eq "Running" } )
  {
      Start-Sleep 1
  }

  $global:Status # here you have your status after job is finished

Get-EventSubscriber | Unregister-Event

另外,不要忘记在不需要时删除工作