How to read an OPC item value in PowerShell
Note: Beginning with version 2021.3, QuickOPC product installation now contains a large set of PowerShell example scripts, and they are included in the conceptual and reference documentation. OPC "Classic", OPC UA Client-Server, and OPC UA PubSub are covered. The User's Guide also provides more information to QuickOPC usage from PowerShell.
The following PowerShell code reads an OPC item and displays its value:
Add-Type -Path OpcLabs.EasyOpcClassic.dll
# Create EasyOPC-DA component
$client = New-Object OpcLabs.EasyOpc.DataAccess.EasyDAClient
# Read item value and display it
$client.ReadItemValue("", "OPCLabs.KitServer.2", "Demo.Single")
We have tested this with QuickOPC 5.40 and PowerShell 3.0. Presumably the same concept works with OPC UA (Unified Architecture) too.
For now, consider this just a proof of concept. So far, we have not specifically targeted PowerShell when designing the components, and there are some rough edges. We have found following issues so far:
- You need to specify a full path to the QuickOPC assemblies, or copy them over (from Assemblies\net452 folder) to your current directory (this is what we have done for the example code above).
- First time the Add-Type is executed, it throws a non-terminating error, indicating a problem loading the assembly. But the execution continues and the read works well. This has to do with the way we have embedded some dependent assemblies, in order to reduce the number of files the developer needs to deal with.
Note: This second problem should be possible to resolve in QuickOPC 2016.2 or later. Select the custom installation option on the setup dashboard, use the "Typical installation (COM)" install type, and then make sure you check "Embedded assemblies" in the list of the installation components.
Contact us should you need further help developing a PowerShell solution with QuickOPC.
Links related to/used when writing this article:
- https://blogs.technet.microsoft.com/heyscriptingguy/2010/11/11/use-powershell-to-work-with-the-net-framework-classes/
- http://powershell.com/cs/blogs/ebookv2/archive/2012/03/27/chapter-20-loading-net-libraries-and-compiling-code.aspx
- http://stackoverflow.com/questions/12923074/how-to-load-assemblies-in-powershell
- http://www.vexasoft.com/blogs/powershell/7255220-powershell-tutorial-try-catch-finally-and-error-handling-in-powershell