4

How do I loop through all items in a JSON file? The current code just writes all names on one big line:

Get-Content -Raw -Path c:\temp\Environments.Generic.json | ConvertFrom-Json | ForEach-Object {
    Write-Host $_.Name
}

json file:

[
   {
      "Name":"EnableRetry",
      "Description":"Enable retry for Webservice Task",
      "Type":"Boolean",
      "Sensitive":false,
      "Value":true
   },
   {
      "Name":"FolderStageFiles",
      "Description":"Location of stage files",
      "Type":"String",
      "Sensitive":false,
      "Value":"d:\\sources\\"
   },
   {
      "Name":"FtpPassword",
      "Description":"Secret FTP password",
      "Type":"String",
      "Sensitive":true,
      "Value":"Welcome1"
   }
]
Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
Joost
  • 1,873
  • 2
  • 17
  • 18

2 Answers2

9

I ended up Select-Object and a ForEach-Object:

$JSON = Get-Content -Raw -Path c:\temp\Environments.Generic.json | ConvertFrom-Json

$JSON | Select-Object -Property Name,Description,Type,Sensitive,Value | ForEach-Object {
    Write-Host $_.Name $_.Value
}
Joost
  • 1,873
  • 2
  • 17
  • 18
  • Looks like a fine solution to me. Apologies for not coming back to you. – Mark Wragg May 12 '17 at 12:11
  • No problem, I took your code as a base and that helped me... Will post the complete code on my blog in a couple of days. – Joost May 12 '17 at 12:16
  • Here is the complete code if someone want to copy it: http://microsoft-ssis.blogspot.com/2017/05/import-and-export-ssis-catalog.html – Joost Jun 08 '17 at 20:35
2

If you do this:

$JSON = Get-Content -Raw -Path c:\temp\Environments.Generic.json | ConvertFrom-Json

$JSON will be a PowerShell object that contains a collection of objects with all of the properties defined in your JSON file.

Enter $JSON at the console and you'll see the contents of this object.

To access specific properties for specific items in the collection you could do (for example):

$JSON | Where {$_.Name -eq 'FolderStageFiles'} | Select -ExpandProperty Value
Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
  • Is there something for looping through the set because I don't know the values of the json file... only the structure (Name, Description, Type, Sensitive and Value). I want to loop through these records and add these values to an SSIS environment like http://microsoft-ssis.blogspot.com/2015/08/deploying-environments-and-variables.html – Joost May 08 '17 at 20:32