Powershell Help

Status
Not open for further replies.

Utildayael

Ars Tribunus Angusticlavius
7,345
Minor Powershell question.

I'm wanting to recursively run through a directory and all subdirectories, read JSON files from them, and merge them all into one massive CSV.

Here's my attempt:
Code:
$output = ".\combined.csv"

Get-ChildItem .\*.recipe -Recurse| Foreach-Object {
   $item = (Get-Content $_ -Raw) | ConvertFrom-Json
   Add-Content -Path $output -Value $item
}

While I can iterate fine and if I output to the console it displays properly, the problem is in writing the CSV. CSV comes out like this:

Code:
@{input=System.Object[]; output=; groups=System.Object[]}

Input, Output, Groups are all properties in the JSON and... have properties of their own with values.

I think the problem is due to each property having 1 or more items which also have values which is where I'm stumped. I'm not entirely sure what the best way to "output" these objects into what is basically a flat array. Input, Output, and Groups are consistent throughout all the JSON files. Input will always have "item" child properties in 1 or more quantities and each of them will have a "count" value. Output will be similar to input. Groups is the easiest as it has 1 or more items under it but no sub-items, ever.

JSON example:

Code:
"input": [
    {
        "item": "item1",
        "count": 25
    },
    {
        "item": "item2",
        "count": 3
    }
],
"output": {
    "item": "someItem",
    "count": 1
},
"groups": [
    "groupA",
    "groupB",
    "groupC"
]



Thoughts? I'm a bit puzzled. :( Hope this all makes sense. :)
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
Easiest fix is to convert it to an intermediary flat powershell object and pipe the whole thing to Export-Csv

Code:
$output = ".\combined.csv"

$files = Get-ChildItem .\*.recipe -Recurse

$jsonItems = $files | Foreach-Object {
   (Get-Content $_ -Raw) | ConvertFrom-Json
}

$customItems = $jsonItems | Foreach-Object {
   $inputItemCount1 = $json.input[0].count
   $outputItemCount = $json.output.count
   [pscustomobject] @{ "inputCount1"=$inputItemCount1; "outputItemCount"=$outputItemCount }
}

$customItems | Export-Csv -Path $output

PS should lazy evaluate the collections, so I like to separate them into individual steps to make breakpointing and debugging in powershell_ise easier.
 

Utildayael

Ars Tribunus Angusticlavius
7,345
Hrm not working quite as expected.

Output CSV ends up looking like:

#TYPE System.Management.Automation.PSCustomObject
"inputCount1","outputItemCount"
"25","28"
"25","28"
"25","28"
[this repeats a total of 28 times, one per file in the directory]

Here's an actual legit file since I'm home now. :)

Code:
{
  "input" : [
    { "item" : "protocitebar", "count" : 12 },
    { "item" : "icecrystal", "count" : 10 },
    { "item" : "ff_silicon", "count" : 12 },
    { "item" : "penumbriteshard", "count" : 20 },
    { "item" : "diamond", "count" : 20 }
  ],
  "output" : {
    "item" : "protobow",
    "count" : 1
  },
  "groups" : [ "prototyper", "weapons", "all" ]
}

Helping a friend with some Starbound mods and he has so many different items its hard to keep track of what is set to what. Goal would be to rip through all the JSONs and put them into some meaningful CSV so I can toss them in Excel and muck with them. Each item has its own JSON file hence the recursion and difficulty in viewing all the data together.

Hopefully that helps a bit with what I'm trying to do? :)
 

Utildayael

Ars Tribunus Angusticlavius
7,345
Also. Outputting $customitems to screen yields something like this along with a bunch of blank lines at the end [not sure what that is about, I'm just writing $customitems to the screen at the end outside of the for loop so... odd. Outputting to grid-view yields exactly what you have in the CSV.

Code:
input                                              output                                             groups                                           
-----                                              ------                                             ------                                           
{@{item=rawminerals; count=25}, @{item=Cerulium... @{item=banehammer; count=1}                        {prototyper, weapons, all}                       
{@{item=blisterbushplantseed; count=6}, @{item=... @{item=blistergun; count=1}                        {prototyper, weapons, all}                       
{@{item=blisterbushplantseed; count=3}, @{item=... @{item=blisterpistol; count=1}                     {prototyper, weapons, all}                       
{@{item=protocitebar; count=8}, @{item=triggera... @{item=ff_bubblegun; count=1}                      {prototyper, weapons, all}                       
{@{item=crystal; count=1000}, @{item=protociteb... @{item=crystallineblade; count=1}                  {prototyper, weapons, all}                       
{@{item=magmawall2; count=250}, @{item=imperviu... @{item=hellfireblade; count=1}                     {prototyper, weapons, all}                       
{@{item=magmawall2; count=150}, @{item=imperviu... @{item=hellfire1hand; count=1}                     {prototyper, weapons, all}                       
{@{item=protocitebar; count=12}, @{item=trigger... @{item=ff_icechucker; count=1}                     {prototyper, weapons, all}                       
{@{item=silk; count=20}, @{item=lasherplantseed... @{item=lasherhook; count=1}                        {prototyper, weapons, all}                       
{@{item=ff_plastic; count=10}, @{item=particlec... @{item=mineralblade; count=1}                      {prototyper, weapons, all}                       
{@{item=ff_plastic; count=20}, @{item=particlec... @{item=mineralcannon; count=1}                     {prototyper, weapons, all}                       
{@{item=ff_plastic; count=30}, @{item=particlec... @{item=mineralcannonadv; count=1}                  {prototyper, weapons, all}                       
{@{item=ff_plastic; count=130}, @{item=particle... @{item=mineralcannonadv2; count=1}                 {prototyper, weapons, all}                       
{@{item=ff_plastic; count=14}, @{item=particlec... @{item=mineralcannonlite; count=1}                 {prototyper, weapons, all}                       
{@{item=particlecannister; count=1}, @{item=ura... @{item=particlegrenade; count=1}                   {prototyper, weapons, all}                       
{@{item=ff_plastic; count=6}, @{item=particleco... @{item=mineralpistol; count=1}                     {prototyper, weapons, all}                       
{@{item=ff_plastic; count=5}, @{item=particleco... @{item=mineralpistollite; count=1}                 {prototyper, weapons, all}                       
{@{item=protocitebar; count=12}, @{item=icecrys... @{item=protobow; count=1}                          {prototyper, weapons, all}                       
{@{item=protocitebar; count=5}, @{item=penumbri... @{item=protopistol; count=1}                       {prototyper, weapons, all}                       
{@{item=ff_silicon; count=120}, @{item=ff_diamo... @{item=siliconspear; count=1}                      {prototyper, weapons, all}                       
{@{item=slime; count=64}, @{item=protocitebar; ... @{item=slimelauncher; count=1}                     {prototyper, weapons, all}                       
{@{item=thornitox; count=12}, @{item=geneticmat... @{item=spikesword; count=1}                        {prototyper, weapons, all}                       
{@{item=thornitox; count=10}, @{item=spikesword... @{item=spikesword2; count=1}                       {prototyper, weapons, all}                       
{@{item=thornitox; count=10}, @{item=spikesword... @{item=spikesword3; count=1}                       {prototyper, weapons, all}                       
{@{item=thornitox; count=10}, @{item=spikesword... @{item=spikesword4; count=1}                       {prototyper, weapons, all}                       
{@{item=thornitox; count=10}, @{item=spikesword... @{item=spikesword5; count=1}                       {prototyper, weapons, all}                       
{@{item=thornitox; count=14}, @{item=protociteb... @{item=thornrifle; count=1}                        {prototyper, weapons, all}                       
{@{item=protocitebar; count=10}, @{item=monster... @{item=warcleaver; count=1}                        {prototyper, weapons, all}
 

Utildayael

Ars Tribunus Angusticlavius
7,345
[url=http:/civis/viewtopic.php?p=27122005#p27122005:2dztqm1v said:
Cookie.Monster[/url]":2dztqm1v]Like pont mentioned, the issue is that your data isn't flat, but you're trying to convert it to a flat (csv) format. JSON and XML output would obviously work, among other alternatives.

Boe Prox had an article describing the issue and a few workarounds a while back.

Cheers!

Indeed! I'm reading the article now and it sounds pretty much identical to what I want to do if I can wrap my bits around really any of the ways he uses to achieve the goal. :)

Thanks for the link!
 

Cookie.Monster

Ars Scholae Palatinae
666
Here's a quick example of what you could do. Ultimately, it comes down to you deciding how to display the output, as there are way too many ways to skin a cat here.

This relies on PowerShell 3 + language features (array.property expands out, pscustomobject accelerator), but I think you must be using this, don't recall the JSON command in PS2.

Code:
#Get the array of json input
    $array = gci D:\*.json | %{get-content -Raw -path $_.fullname} | convertfrom-json

$results = foreach($row in $array){
    #Loop through input.  For each, show item:count, separated by semicolon
        $inp = (
            $row.input | %{
                "$($_.item):$($_.count)"
            }
        ) -join ";"

    #Same idea as input
        $out = (
            $row.output | %{
               "$($_.item):$($_.count)"

            }
        ) -join ";"

    #For groups, just join
        $groups = $row.groups -join ","

    #Build your flat custom object
        [pscustomobject]@{
            Input = $inp
            Output = $out
            Groups = $groups
        }

}

Example output with your dummy file and another modified dummy file:
Code:
Input                                                                               Output        Groups                   
-----                                                                               ------        ------                   
protocitebar:12;icecrystal:10;ff_silicon:12;penumbriteshard:20;diamond:20           protobow:1    prototyper,weapons,all   
protocitebar1:112;icecrystal1:110;ff_silicon1:112;penumbriteshard1:120;diamond1:120 protobow1:111 prototyper1,weapons1,all1
 

Utildayael

Ars Tribunus Angusticlavius
7,345
That should work. I tried using the script provided in the link but it isn't happy with something.

Code:
$path = ".\combined.csv"

$files = Get-ChildItem .\*.recipe -Recurse

$jsonItems = $files | Foreach-Object {
   (Get-Content $_ -Raw) | ConvertFrom-Json
}

$Output = 'input','output', 'groups'

$jsonitems | Select-Object $Output | Convert-OutputForCSV -OutputPropertyType comma | Export-Csv -NoTypeInformation -Path $path

I was really excited when I saw his "stack" option as that is a "no work required in Excel" option but... the output goes wonky and the comma option seems to ignore input completely for some reason, ie:

"input","output","groups"
", , , , ","@{item=banehammer; count=1}","prototyper, weapons, all"



That said... on your script... and this is probably a n00b question. What is the name of the object if I wanted to shoot it to CSV [or whatnot]?
 
Status
Not open for further replies.