Challenge: Wrote powershell code that will count the total number of events for each tag found in some .csv file between 01/01/2024 and 01/15/2024. The code errors with the following:
Cannot convert argument "timeRange", with value: "2024-08-13", for "RecordedValues" to type "OSIsoft.AF.Time.AFTimeRange": "Cannot convert the
"2024-08-13" value of type "System.String" to type "OSIsoft.AF.Time.AFTimeRange"."
At C:pipointeventextractscriptpipoint-event-extract.ps1:25 char:5
+ $eventCount = $piPoint.RecordedValues($startTime, $endTime, [OSIs ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
Cannot make heads or tails as to what to pass instead.
Desired Outcome: to be able to pass a start-date, and end-date and the script to total all events for listed set of pitags from another .csv file.
The Code
cls
# Load the necessary PI AF SDK assemblies
$AFSDKAssembly = [Reflection.Assembly]::LoadWithPartialName("OSIsoft.AFSDK")
# Define the PI Server and time range
$piServerName = "HYDRAN-PISRV001"
$startTime = "2024-08-13"
$endTime = "2024-08-14"
# Read the PI Tags from the CSV file
$piTags = Import-Csv -Path "C:pipointeventextractdatapipoints-events-extract.csv" | Select-Object -ExpandProperty PointName
# Create a list to store the results
$results = @()
# Connect to the PI Server
$piServers = New-Object OSIsoft.AF.PI.PIServers
$piServer = $piServers[$piServerName]
$piServer.Connect()
# Loop through each PI Tag and get the total number of events
foreach ($tag in $piTags) {
$piPoint = [OSIsoft.AF.PI.PIPoint]::FindPIPoint($piServer, $tag)
$eventCount = $piPoint.RecordedValues($startTime, $endTime, [OSIsoft.AF.Data.AFBoundaryType]::Inside, $null, $false).Count
# Add the result to the list
$results += [PSCustomObject]@{
"PI Server Name" = $piServerName
"Tag" = $tag
"Start Time" = $startTime
"End Time" = $endTime
"Total Events" = $eventCount
}
}
# Define the output file path with the current date and time
$outputFilePath = "C:pipointeventextractreportpipointeventreport-hvn" + (Get-Date).ToString("yyyyMMdd_HHmmss") + ".csv"
# Export the results to a CSV file
$results | Export-Csv -Path $outputFilePath -NoTypeInformation
Write-Output "Report generated: $outputFilePath"