Have PowerShell pass results to Pentaho - powershell

I have a PowerShell script that processes a json string. My goal is to have this pass a resultset to Pentaho so I can process it and put it in a database table.
My PowerShell script works as expected outside of Pentaho. I can parse the files and get the information I need without any issues. It's when I try to pass those values is when Pentaho returns goofy results.
Here is my script
$scriptMode = 'GetFileInfo'
$json = '{
"building": [
{
"buildingname": "NAPA Auto Parts",
"files": [{
"sheets": [{
"name": "BATTERY",
"results": [{
"filename": "BATTERY - 1679568711.xlsx",
"sku": "1679568711"
}
]
}
],
"name": "2.15.19.xlsx",
"status": "processed",
"fileId": "c586bba6-4382-42c4-9c29-bffc6f7fe0b6"
}, {
"name": "Oct-Nov 2018 11.30.18.xlsx",
"errors": ["Unknown sheet name: TOILET PLUNGER"],
"status": "failed",
"fileId": "afa7c43f-26dc-421c-b2eb-45ad1e899c42"
}
]
},
{
"buildingname": "O''Reily Auto Parts",
"files": [{
"sheets": [{
"name": "ALTERNATOR",
"results": [{
"filename": "ALTERNATOR - 6.3.19 1629453444.xlsx",
"sku": "1629453444"
}
]
}, {
"name": "OIL FILTER",
"results": [{
"filename": "OIL FILTER - 6.3.19 1629453444.xlsx",
"sku": "1629453444"
}
]
}
],
"name": "6.3.19.xlsx",
"status": "processed",
"fileId": "647089fe-9592-4e2b-984f-831c4acd4d9c"
}
]
}
]
}'
$psdata = ConvertFrom-Json -InputObject $json
IF ($scriptMode -eq "GetFileInfo") {
$psdata.building | foreach-Object {
foreach ($File in $_.files)
{
[PSCustomObject]#{
BuildingName = $_.buildingname
FileName = $File.name
fileId = $File.fileId
Status = $File.status}
}
}
}
ElseIF ($scriptMode -eq "GetErrorInfo") {
$psdata.building | foreach-Object {
foreach ($File in $_.files)
{
[PSCustomObject]#{
BuildingName = $_.buildingname
Errors = $File.errors
SheetName = $File.sheets.name
fileId = $File.fileId} | Where-Object {$_.errors -ne $null}
}
}
}
And here's how I have my transformation setup. I have a table input query that will set the run command for PowerShell based on what I want the script to do (either get file info or get error info).
Then I have the "Execute a process" step run the PowerShell command
This is what is returned in Pentaho vs what PowerShell returns
I'm expecting the results to be returned exactly as PowerShell returns them. I'm hoping I can accomplish this without exporting the data to another format. We have had nothing but issues with the Json Input step in Pentaho, so we chose PowerShell over the "Modified Javascript Value" step in Pentaho.
Any idea how I can get this to return a result set (like a SQL query would return) back to Pentaho?

Most likely your result set is returning the entire thing, just not "tabled" as you expected, it's probably returning the entire table all summed up in one long text format, but still having all the line breaks / column breaks.
Try using Split steps in your pentaho flow to work on the returned String. First off, try using a "Split field to rows" with the delimiter as "${line.separator}".
From there all you to do is pretty much split the whole thing until it is a table in pentaho.

Related

issues PowerShell POST request with body

I have a bit issue with powershell + invoke-webrequest
This is my body
$pram = #{
"name": "MDE.Windows",
"id": "$resourceId/extensions/MDE.Windows",
"type": "Microsoft.Compute/virtualMachines/extensions",
"location": "westeurope",
"properties": {
"autoUpgradeMinorVersion": true,
"publisher": "Microsoft.Azure.AzureDefenderForServers",
"type": "MDE.Windows",
"typeHandlerVersion": "1.0",
"settings": {
"azureResourceId": "$resourceId",
"defenderForServersWorkspaceId": "$subscriptionId",
"vNextEnabled": "true",
"forceReOnboarding": true,
"provisionedBy": "Manual"
},
"protectedSettings": {
"defenderForEndpointOnboardingScript": "$defenderForEndpointOnboardingScript"
}
}
}
I don't get watch wrong with my body because by looking examples from google this should be right but it still ouputs red
I have tried also with #"{ }"#, #'{ }'#, { }, "{ }" but no matter what I do it is more or less red.
I think your mistaking powershell hash tables for json. Normally you would create a hashtable using powershell syntax, then convert that object into Json. eg
$pram = #{
name= "MDE.Windows";
id= "$resourceId/extensions/MDE.Windows";
} | ConvertTo-Json
You can now pass the json encoded value of $parm to Invoke-WebRequest.
The other option is to create a String and write the JSON yourself:
$paramString = '{"id": "/extensions/MDE.Windows", "name": "MDE.Windows"}'
(but the first solution is probably the solution your looking for).

Convert JSON-String to proper Object in Powershell

I spend 3 hours debugging, but I don't get the rootcause.
I have text (in JSON Format) in a variable. I convert it with "Convert-From-JSON" to an actual object. I was hoping that I can then work with the properties of the object. But it does not work :( It seems that the conversion only gives me two tables (status and data). What am I doing wrong?
My code:
$results = {
"status": "FINISHED",
"data": {
"results": [
{
"id": "11565C230500",
"custom": {
"image": "XXXX",
"name": "XXXX",
"articleNumber": "4032423423505"
}
},
{
"id": "22739L5F16243",
"custom": {
"image": "XXXX",
"name": "XXXX",
"articleNumber": "4032423423505"
}
},
{
"id": "3304332724004",
"custom": {
"image": "XXXX",
"name": "XXXX",
"articleNumber": "4032423423505"
}
}
]
}
}
Now putting it as Object:
$resultObject = ConvertFrom-JSON -InputObject $result
Now trying to retrieve:
$resultObject.id | where {$_.id -eq '11565C230500'}
As it is now, you define $results as script block where it should be a string:
$results = #'
{
"status": "FINISHED",
"data": {
"results": [{
"id": "11565C230500",
"custom": {
"image": "XXXX",
"name": "XXXX",
"articleNumber": "4032423423505"
}
},
{
"id": "22739L5F16243",
"custom": {
"image": "XXXX",
"name": "XXXX",
"articleNumber": "4032423423505"
}
},
{
"id": "3304332724004",
"custom": {
"image": "XXXX",
"name": "XXXX",
"articleNumber": "4032423423505"
}
}
]
}
}
'#
Now you can convert it from the JSON string
$resultObject = $results | ConvertFrom-Json
Then, to parse out the nested property, you need to follow the data structure:
$resultObject.data.results | Where-Object {$_.id -eq '11565C230500'}
will give you this:
id custom
-- ------
11565C230500 #{image=XXXX; name=XXXX; articleNumber=4032423423505}
If you want to get the articleNumber from the custom object that contains, dig deeper still:
($resultObject.data.results | Where-Object {$_.id -eq '11565C230500'}).custom.articleNumber
which will return 4032423423505
Assuming the json is single quoted in that example, otherwise it's a scriptblock, and "$results" is used in place of "$result", the id property is underneath data.results. You couldn't examine the id property with where-object if you already expanded it. That's an alternate form of where-object. I'm expanding the "custom" property with the foreach-object alias "%". Note one id number is shorter. Beware convertto-json's default depth of 2.
$results = '{"status":"FINISHED","data":{"results":[
{"id":"11565C230500", "custom":{"image":"XXXX","name":"XXXX","articleNumber":"4032423423505"}},
{"id":"22739L5F16243","custom":{"image":"XXXX","name":"XXXX","articleNumber":"4032423423505"}},
{"id":"3304332724004","custom":{"image":"XXXX","name":"XXXX","articleNumber":"4032423423505"}}
]}}'
$resultObject = ConvertFrom-JSON -InputObject $results
$resultObject.data.results | where id -eq 11565C230500
id custom
-- ------
11565C230500 #{image=XXXX; name=XXXX; articleNumber=4032423423505}
$resultobject.data.results | where id -eq 11565C230500 | % custom
image name articleNumber
----- ---- -------------
XXXX XXXX 4032423423505

How to print the contents of the objects taking one value as input in powershell?

I need to display the contents related to each id number by taking id as input. The original format was in json, as below:
{
"ids": [
{
"id": "121100",
"Libraries": [
"cpa_sample_code_s.so",
"stv_test_code_s.so"
],
"Commands": [
"qaeMemInit",
"icp_sal_userStartMultiProcess(\"SSL\",CPA_FALSE)",
"rsaPerformanceTest(1,0x02,2,10,1000) [RSA API]"
],
"Label": "rsaPerformanceTest-Test"
},
{
"id": "121103",
"Libraries": [
"cpa_sample_code_s.so",
"stv_test_code_s.so"
],
"Commands": [
"qaeMemInit",
"icp_sal_userStartMultiProcess(\"SSL\",CPA_FALSE)",
"dhPerformanceTest(1,0x02,10,10000)"
],
"Label": "dhPerformanceTest-Test"
},
{
"id": "121202",
"Libraries": [
"cpa_sample_code_s.so",
"stv_test_code_s.so"
],
"Commands": [
"qaeMemInit",
"icp_sal_userStartMultiProcess(\"SSL\",CPA_FALSE)",
"runDcTestPerf(3,0,2,1,1,1,65536,1,100)"
],
"Label": "runDcTestPerf-Test"
}
]
}
I converted the above format from a json file to the below mentioned format in $myVar. My variable has a hash table but I am unable to display the values using $myvar["id"]. I am very new to powershell. Can anyone please help?
$myFile = get-content C:\Users\ssc\Desktop\powershell\activity.json
$myvar = $myFile | ConvertFrom-Json
PS C:\Windows\system32> $myvar
ids
---
{#{id=121100; Libraries=System.Object[]; Commands=System.Object[]; Label=rsaPerformanceTest-Test}, #{id=121103; Libraries=System.Object[]; Commands=System.Object[]; Label=dhPerformanceTest-Test}, #{id=121202; Libraries=System.Object[]; Commands=System.Object[]; Label=runDcTestPerf-Test}}
PS C:\Windows\system32>
$myvar.ids currently contains an array of objects - but you can populate your own hashtable, using the id property as the key, like this:
$myHashtable = #{}
$myvar.ids |ForEach-Object { $myHashtable[$_.id] = $_ }
At which point you should be able to resolve each by id:
PS ~> $myHashtable["121100"]
id Libraries Commands
-- --------- --------
121100 {cpa_sample_code_s.so, stv_test_code_s.so} {qaeMemInit, icp_sal_userStartMultiProcess("SSL",CPA_FALSE), ...}

Parse JSON output into a CSV file using Powershell

I'm using PowerShell to extract data via an API and would like to parse the JSON into a CSV file. How would I parse each of the JSON results into a CSV structure like this:
$Date, $app, $pagename, $range1, $range1_value
$Date, $app, $pagename, $range2, $range2_value
$Date, $app, $pagename, $range3, $range3_value
The JSON looks like this:
{
"fields": [
{
"label": "app",
"field": "app",
"type": "string"
},
{
"label": "pagename",
"field": "pagename",
"type": "string"
},
{
"label": "range1",
"field": "count(*)",
"type": "integer",
"aggregation": "filter"
},
{
"label": "range2",
"field": "count(*)",
"type": "integer",
"aggregation": "filter"
},
{
"label": "range3",
"field": "count(*)",
"type": "integer",
"aggregation": "filter"
}
],
"results": [
[
"application1",
"loginpage",
41425,
41266,
18869
],
[
"application2",
"loginpage",
7424,
7113,
2905
]
],
"moreData": false,
"schema": "record"
}
I've tried various methods (e.g. Convertto-JSON and Convertfrom-JSON) but I don't seem to be able to connect the 'fields' and 'results' together into a hashtable. I was hoping I could create it as a $JSON object and then iterate through each result like $JSON[0..1].
Let's start by parsing your input data!
Use a for loop to iterate over the individual array items in the results values, then use the index to resolve the type and label name from the fields list:
# Convert from json
$data = $jsonString |ConvertFrom-Json
# Set up a type table for easy conversion
$typeTable = #{'integer' = [int]}
# Iterate over each row in the results
$results = foreach($values in $data.results){
# Create dictionary to hold property values for the row
$Properties = [ordered]#{}
for($index = 0; $index -lt $data.fields.Count; $index++){
# Resolve field metadata by index
$field = $data.fields[$index]
# Take type mappings into account and write to $Properties dictionary
if($typeTable.ContainsKey($field.type)){
$Properties[$field.label] = $values[$index] -as $typeTable[$field.type]
}
else{
$Properties[$field.label] = $values[$index]
}
}
# Output structured object
[PSCustomObject]$Properties
}
Now that we have nice objects we can work with, we can use Select-Object and Export-Csv to create the desired output format:
$results |Select-Object #{Name='Date';Expression={Get-Date -Format yyyyMMdd}},app,pagename,#{Name='2000';Expression={'2000'}},range3 |Export-Csv -Path .\path\to\output.csv -NoTypeInformation

Building a nested dictionary/hash tables in powershell displays "System.Collections.Hashtable"

I'm trying to create a body for a webrequest which is in the form of a nested dictionary.
$body +=#{}
$body["tables"] = #()
$body["tables"] += #{}
$body["tables"][0]["id"] += #{}
$body["tables"][0]["id"]["columnId"] = "1"
$body["tables"][0]["id"]["fieldType"] = "1"
$body["tables"][0]["textFilter"] = #{"value" = "123"}
$body2Json = ConvertTo-Json $body
When I try to print this, I get the following:
{
"tables": [
{
"id": "System.Collections.Hashtable",
"textFilter": "System.Collections.Hashtable"
}
]
}
Not sure what am I doing wrong here, still new to powershell
You created a pretty complex, multi-node PowerShell object, but the ConvertTo-Json cmdlet only converts the first two levels of depth before it stops.
Fortunately, You can control this behavior with the -Depth parameter like so:
ConvertTo-Json $body -Depth 5
{
"tables": [{
"id": {
"columnId": "1",
"fieldType": "1"
},
"textFilter": {
"value": "123"
}
}]
}