How to subscribe to OPC data changes in PowerShell
From OPC Labs Knowledge Base
The following PowerShell code subscribes to an OPC item and displays the incoming data changes:
Add-Type -Path OpcLabs.EasyOpcClassic.dll
# Create EasyOPC-DA component
$client = New-Object OpcLabs.EasyOpc.DataAccess.EasyDAClient
# Hook events
Register-ObjectEvent -InputObject $client -EventName ItemChanged -Action { Write-Host $EventArgs }
# Subscribe
$client.SubscribeItem("", "OPCLabs.KitServer.2", "Demo.Single", 1000)
We have tested this with QuickOPC 5.40 and PowerShell 3.0.
Note: For some issues and limitations, see How to read an OPC item value in PowerShell.
Note: A memory leak related to event handling has been observed under some circumstances in PowerShell (and QuickOPC 2017.2). Workaround is to use the "event pull" mechanism in QuickOPC, instead of hooking event handlers.
Links related to/used when writing this article:
- https://blogs.technet.microsoft.com/heyscriptingguy/2011/06/16/use-asynchronous-event-handling-in-powershell/
- http://www.get-blog.com/?p=189
- http://serverfault.com/questions/270568/need-to-add-a-wait-command-to-a-powershell-script
- http://stackoverflow.com/questions/1478545/handling-events-with-powershell