Why am I getting a System.Reflection.TargetInvocationException in PowerShell when using the AFSDK GetValue function on PI Point attributes?

I am trying to write a script in PowerShell that filters a list of attributes from one of our PI AF databases to only contain attributes with a certain value. This script works as intended when the attributes I'm searching have no data reference (<None> in PI AF), but it fails for PI Point attributes.

 

The failure occurs when I run the GetValue() function on a PI Point attribute, Instead of returning a value, it returns a System.Reflection.TargetInvocationException. If I setup a connection to the PI Archive that the PI Point is stored on and then use the Get-PIValue function, I am able to retrieve the value without issue. I also have full admin rights to the PI AF database so I don't suspect a security issue but I'm at a loss.

 

Any ideas on what is causing this exception and how to resolve it so I can get a real value? Perhaps I'm using the GetValue() function incorrectly. My code is below along with the output of the GetValue() function. I'd appreciate any insight!

 

Code:

# Defines other inputs which will later be used as function parameters.

$AFServer = "<AF Server Name>"

$AFDatabase = "<AF Database Name>"

$Category = "Category:='MB - Overridable'"

$Name = "Name:='*'"

$Root = "Root:='<Root Element>'"

$Template = ""

$NameFilter = @("Base Gravity","Molecular Weight")

$AttributeName = "Override Value Check"

 

# Loads the assembly with the AFSDK functions needed to search and backfill analyses.

[Reflection.Assembly]::LoadFile("C:&#92;Program Files (x86)\PIPC\AF\PublicAssemblies\4.0\OSIsoft.AFSDK.dll")

 

# Sets up a connection to the PI AF server and database specified by the user.

$Servers = New-Object([OSIsoft.AF.PISystems])

$Server = $Servers | Where-Object Name -eq $AFServer

$Server.Connect()

$Database = $Server.Databases | Where-Object Name -eq $AFDatabase

 

# Defines the AFElementSearch object with the required search criteria. An attribute search cannot be used directly because it is necessary to search by an element root.

$SearchName = "Element Search"

$SearchString = "$Name $Template $Category $Root"

$Search = New-Object([OSIsoft.AF.Search.AFElementSearch]) -ArgumentList $Database, $SearchName, $SearchString

 

# Identifies a list of elements that match the search criteria after applying a filter.

$FilterList = @("Base Gravity","Molecular Weight")

$Elements = $Search.FindObjects(0,$True)

 

# Identifies a list of elements that match the search criteria after applying a filter.

$FilterList = @("Base Gravity","Molecular Weight")

$Elements = $Search.FindObjects(0,$True)

$Elements = ($Elements | Where-Object {$NameFilter -contains $_.Name})

 

# Extracts the desired attribute from each element and a group of the attributes that match the defined criteria.

$Attributes = $Elements | Get-AFAttribute -Name $AttributeName

$Matches = $Attributes | Where-Object {($_.GetValue()).Value -eq 1}

$Value = $Attributes[10].GetValue()

 

Output:

Status     : Bad

IsGood     : False

Substituted  : False

Questionable  : False

Annotated   : False

Timestamp   : 9/5/2024 5:02:14 PM

ValueType   : System.Reflection.TargetInvocationException

ValueTypeCode : Object

Value     : System.Reflection.TargetInvocationException: Exception has been thrown by the 

         target of an invocation. ---> System.EntryPointNotFoundException: Unable to 

         find an entry point named 'SessionManager_AddOIDCTokenAcquisitionCallback' in 

         DLL 'PIInterop'.

          at OSIsoft.PI.Net.UnsafeNativeMethods.SessionManager.AddOIDCTokenAcquisition

         Callback(IntPtr sessionManager, IntPtr oidcTokenAcquisitionPointer, Int32 

         managedThreadId)

          at OSIsoft.PI.Net.SessionManager..ctor()

          --- End of inner exception stack trace ---

          at OSIsoft.AF.PI.PIException.ConvertAndThrowException(PIServer piServer, 

         Exception ex, String message)

          at OSIsoft.AF.PI.PIServer.RemoteConnect(AFConnectionPreference preference, 

         NetworkCredential credential, PIAuthenticationMode authenticationMode)

          at OSIsoft.AF.PI.PIServer.InternalConnect(Int32 numRetries, IWin32Window 

         owner, AFConnectionPreference preference, NetworkCredential credential, 

         PIAuthenticationMode authenticationMode, Boolean checkConnectingAsSameUser)

          at OSIsoft.AF.PI.PIServer.AutoConnect(Boolean allowDirectConnect, Boolean 

         force)

          at OSIsoft.AF.PI.PIPoint.FindPIPoint(PIServer piServer, String pointName)

          at OSIsoft.AF.Asset.DataReference.SinglePIPointResolvedConfiguration.Resolve

         PIPointInternal(IDataReference dataReference, PIServer piServer, 

         SinglePIPointConfiguration config, String resolvedTagName, PIPoint& piPoint)

          at OSIsoft.AF.Asset.DataReference.SinglePIPointResolvedConfiguration.Resolve

         PIPoint(PIPoint& piPoint)

          at OSIsoft.AF.Asset.DataReference.PIPointDR.GetValueTime(PIPointResolvedConf

         iguration resolvedConfigBase, AFTime time)

          at OSIsoft.AF.Asset.DataReference.PIBaseDR.GetValue(Object context, Object 

         timeContextArg, AFAttributeList inputAttributes, AFValues inputValues)

          at 

         OSIsoft.AF.Data.Query.SingleValueQuery.ExecuteQueryForSource(AFDataReference 

         dataReference)

          at OSIsoft.AF.Data.Query.SingleValueQuery.OSIsoft.AF.Data.IExecutableDataQue

         ry<OSIsoft.AF.Asset.AFValue>.ExecuteQueryForSource(AFAttribute attribute, 

         AFDataReference dataReference, UOM desiredUOM)

          at OSIsoft.AF.Data.SingleInputVisitor`1.VisitSource(AFAttribute attribute, 

         IExecutableDataQuery`1 query, AFDataReference dataReference)

          at OSIsoft.AF.Data.InputEvaluatingVisitor`2.OSIsoft.AF.Data.IInputVisitor<TI

         dentifier,TValue>.VisitSourceDataReference(AFAttribute attribute, 

         IExecutableDataQuery`1 query, AFDataReference dataReference)

UOM      : 

Attribute   : Override Value Check

PIPoint    : 

AdditionalInfo : 

Parents
  • Hello ​ ,

    please accept my apologies if the salutation sounds like an insult but it was you choosing your SSO alias. Wink

    Your code wasn't working for me and I went through it line-by-line, removed the things not needed from my point of view and made some additional adjustments.

    # Defines other inputs which will later be used as function parameters.
    $AFServer = "MyAFServer"
    $AFDatabase = "Sandbox"
    $Category = "Category:='Test'"
    $Name = "Name:='*'"
    $Root = "Root:='PISquare'"
    $Template = ""
    $AttributeName = "CDT158"
    
    # Load the AFSDK assembly in Powershell
    [System.Reflection.Assembly]::LoadWithPartialName("OSIsoft.AFSDK") | Out-Null
    
    # Sets up a connection to the PI AF server and database specified by the user.
    $Servers = New-Object([OSIsoft.AF.PISystems])
    $Server = $Servers[$AFServer] 
    $Database = $Server.Databases[$AFDatabase]
    
    # Defines the AFElementSearch object with the required search criteria. An attribute search cannot be used directly because it is necessary to search by an element root.
    $SearchName = "Element Search"
    $SearchString = "$Name $Template $Category $Root"
    $Search = New-Object -TypeName OSIsoft.AF.Search.AFElementSearch -ArgumentList $Database, $SearchName, $SearchString
    # Execute the search
    $Elements = $Search.FindObjects(0,$True)
    
    # Extracts the desired attribute from each element and a group of the attributes that match the defined criteria.
    foreach ($Element in $Elements)
    {
        $Attribute = $Element.Attributes[$AttributeName]
        $Value = $Attribute.GetValue();
        $Attribute.Name + " " + $Value.Value + " at " + $Value.Timestamp 
    }

    The above code is working for me now but may still not be working for you.

    The error you are getting suggest some issue with OIDC which tells me that you have PI AF Client 2023 or later installed.

    PI Server 2023 is a platform release introducing claims-based authentication with OIDC being enabled through AVEVA Identity Manager. You still should be able to use AF Client 2023 and the included AF SDK against earlier PI Server versions. However, the error you are getting indicates the issue is with the connection against the PI Data Archive. While I believe you have a valid Mapping to a PI Identity in AF, you likely missed creating a mapping on the PI Data Archive host. Your interaction with AF Server appears to be ok until you ask the Attribute value. I guess, the Attribute is configured with the PI Point Data Reference which will result into this Data Reference being executed against the PI Data Archive at the very moment you request the value. Different Authentication methods will be tried but if everything fails, you receive an exception like the one you are facing.

  • Hi ​! Thanks for the reply. And no worries on the username haha (its an old family nickname).

     

    I ran your code and still got the OIDC error so I think you're right that it has something to do with my connection to the archive.

     

    One strange thing I wanted to mention before digging into that much farther is that I am able to connect to the PI archive using the Connect-PIDataArchive command and then get values for the same PI Points in the attribute data references from my previous code using the Get-PIValue command.

     

    Does this mean my connection to the PI data archive is okay or could there still be a problem? Is there any other reason I'd be getting the OIDC error if my mapping to the PI archive is working?

Reply
  • Hi ​! Thanks for the reply. And no worries on the username haha (its an old family nickname).

     

    I ran your code and still got the OIDC error so I think you're right that it has something to do with my connection to the archive.

     

    One strange thing I wanted to mention before digging into that much farther is that I am able to connect to the PI archive using the Connect-PIDataArchive command and then get values for the same PI Points in the attribute data references from my previous code using the Get-PIValue command.

     

    Does this mean my connection to the PI data archive is okay or could there still be a problem? Is there any other reason I'd be getting the OIDC error if my mapping to the PI archive is working?

Children
No Data