Dear PI Geeks,


This blog post is inspired by Ernst Amort with his comment to How to write PI Data to files in XML format?


The examples offered to write files in XML format require only slight modification to accomplish this. For this reason, I am sticking with a single example.


# Load the AF SDK assembly through reflection
[Reflection.Assembly]::LoadWithPartialName("OSIsoft.AFSDK") | Out-Null

# Connect to the default PI Data Archive
[OSIsoft.AF.PI.PIServers] $piSrvs = New-Object OSIsoft.AF.PI.PIServers
[OSIsoft.AF.PI.PIServer] $piSrv = $piSrvs.DefaultPIServer

# Define array of PI Point Names
$piPointNames = @()
$piPointNames = $piPointNames + "SINUSOID"
$piPointNames = $piPointNames + "CDT158"

# Define the time range for data retrieval
[OSIsoft.AF.Time.AFTimeRange] $timeRange = New-Object OSIsoft.AF.Time.AFTimeRange("*-4h", "*")

# Create one XML file for each PI Point
foreach ($piPointName in $piPointNames)
    # Load PI Point 
    [OSIsoft.AF.PI.PIPoint] $piPoint = [OSIsoft.AF.PI.PIPoint]::FindPIPoint($piSrv, $piPointName)

    # Retrieve values
    [OSIsoft.AF.Asset.AFValues] $piValues = $piPoint.RecordedValues($timeRange, [OSIsoft.AF.Data.AFBoundaryType]::Inside, $null, $true, 1000)

    # Define output file path and name
    $OutputFile = "C:\Temp\JSON\" + $piPointName + ".json"

    # Inform the user
    Write-Host $piValues.Count " values will be written to " $OutputFile

    # Convert $piValues to JSON 
    $JsonValues = ConvertTo-Json -InputObject $piValues 

    # Save the $JsonValues object to file
    Out-File -FilePath $OutputFile -InputObject $JsonValues


The resulting files again have all properties and the belonging values of the AFValue object.



The most simple approach to simplify the output is likely to reduce the depth. This can be accomplished by using the -Depth parameter offered by ConvertTo-JSON (also an option with ConvertTo-Xml).


    # Convert $piValues to JSON 
    $JsonValues = ConvertTo-Json -InputObject $piValues -Depth 1


The resulting file shows a format like this.