Powershell - 从自定义事件处理程序访问全局同步哈希 table

Powershell - Access global synchronized hash table from custom event handler

我正在尝试访问事件处理程序脚本块中的 $syncHash,但似乎什么也没发生。有办法吗?

$syncHash = [hashtable]::Synchronized(@{})
$syncHash.PostPocess = {
    [string]$path = $event.messagedata
    ...
    # trying to access $syncHash here, but failed
    ...
}

Register-EngineEvent -SourceIdentifier Process_Result -Action $syncHash.PostPocess
New-Event -SourceIdentifier Process_Result -MessageData $path

谢谢,

您的事件脚本块无权访问您从中注册事件的初始 PowerShell 环境。

一种解决方案是通过事件的 MessageData 处理程序传递同步哈希,这是您修改后的代码:

$syncHash = [hashtable]::Synchronized(@{})

$syncHash.PostPocess = {

    # Your $path variable is now in the first cell of the array $event.messagedata
    [string]$path = $event.messagedata[0]

    ...

    # Should display 'True', as $event.MessageData[1] is now your initial $syncHash
    echo $event.MessageData[1].IsSynchronized

    ...

}

Register-EngineEvent -SourceIdentifier Process_Result -Action $syncHash.PostPocess

New-Event -SourceIdentifier Process_Result -MessageData @($path, $syncHash)

对于数组,您可以使用 $eventMessageData 成员作为参数行。