As a quick follow up to my post yesterday CAPA 4.3.2 - Passing complex variables to PowerShell scripts!, I thought I'd show one of the ways that I'm now using to get complex data out of PowerShell and back into CAPA.
In the several years I have been using CAPA, I have come up with about a half-dozen different ways to pass data back from PowerShell to CAPA. But I think this is the one that I have so far found to be one of the quickest and easiest to use.
The whole process involves 4 pretty basic steps:
- Creating a PowerShell Object to hold your results
- Converting the PowerShell Object to JSON
- Writing the JSON text to the ScriptOutput
- Once back in CAPA, parsing that JSON text directly into a ValueMap.
I'll attach the PowerShell and JavaScript code at the bottom, so feel free to skip ahead if you are the DIY kind of person.
The sample PowerShell code I have attached is a simple example to show how to generate the output.
This example will either return a failure status (if the drive doesn't exist) with a simple error message like this:
{
"status": "failure",
"message": "Cannot find drive. A drive with the name ZZ does not exist."
}
Or a status of success, with a complex result like this:
{
"status": "success",
"result": [
{
"Name": "adb",
"Parent": "",
"Exists": true,
"Root": "C:\\",
"FullName": "C:\\adb",
....
}
]
}
This output is then easily converted to a ValueMap via convertJson() and you end up with something that looks like this:
Hopefully this helps someone out,
Ian
### START OF POWERSHELL SAMPLE SCRIPT ###
try
{
<# Do something here #>
#$x = Get-ChildItem C:\ -ErrorAction Stop #Should exit success
$x = Get-ChildItem ZZ:\ -ErrorAction Stop #Should exit failure
$Result_Value = New-Object PSObject
$Result_Value | add-member Noteproperty status "success"
$Result_Value | add-member Noteproperty result $x
$output = $Result_Value | ConvertTo-Json
Write-Host $output
Exit 0
}
catch
{
$Result_Value = New-Object PSObject
$Result_Value | add-member Noteproperty status "failure"
$Result_Value | add-member Noteproperty message $_.Exception.Message.tostring()
$output = $Result_Value | ConvertTo-Json
Write-Host $output
Exit 1
}
### END OF POWERSHELL SAMPLE SCRIPT ###
//START OF CAPA POST-EXCEUTION CODE SAMPLE SCRIPT
try
{
var process_output = newValueMap();
process_output = convertJson(Process[OpName].scriptOutput);
if(process_output.status != "success")
{
setOperatorStatus("Failure",-1,process_output.status.toString());
}
Process[OpName].process_output = process_output;
Process.results = process_output.result;
}
catch(x)
{
setOperatorStatus("Failure",-1,x.toString());
}
//END OF CAPA POST-EXCEUTION CODE SAMPLE SCRIPT