powershell - 从PowerShell中的后台作业中调用的函数获取返回值

标签 powershell powershell-2.0 powershell-3.0 powershell-4.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})

这件事杀了我...

最佳答案

您这里需要计时器吗?完成工作后您能得到结果吗?

  $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

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

关于powershell - 从PowerShell中的后台作业中调用的函数获取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33701785/

相关文章:

json - Azure CLI Rest 编码问题(德语变音符号)

arrays - 如何处理 “distorted” array-output

powershell - 在安装 Sharepoint 2010 之前卸载 PowerShell 1.0

powershell-2.0 - 禁用通过 Powershell 启用的 SNMP 状态

excel - 为什么在 VBScript 中写入 Excel 单元格值速度很快,但在 PowerShell 中写入速度很慢?

powershell - 用于列出目录中所有文件和文件夹的 PowerShell 脚本

Powershell 脚本根据创建时间戳将文件移动到年/月文件夹中

arrays - Powershell 从出现 $N 次的 IP 数组创建逗号分隔列表

Powershell:替换为西里尔字符串

vba - Excel 工作簿连接使文件大小变大