display Json nested arrays in powershell - json

I've written one JSON script with nested arrays and trying to display the all the data based on title. but unfortunately i couldn't make that happen. i'm placing my JSON and powershell code below. kindly help me.
JSON code:
{
"Deploy": {
"ENV": "DIT",
"Servers": [
{
"Webservers": [
{
"Server": ["Server1","Server2"],
"site": ["website1","WebSite2"],
"VDIR": ["WebSite1","WebSite2"]
},
{
"Server": ["Server1","Server2"],
"site": ["WebSite1","WebSite2"],
"VDIR": ["WebSite1","WebSite2"]
}
]
},
{
"Winservers": [
{
"Server": ["Server1","Server2"],
"winService": ["service1","service2"]
},
{
"Server": ["Server3","Server4"],
"winService": ["service3","service4"]
}
]
}
]
}
}
Powershell Code:
$Deploy=(Get-Content D:\Deploy.json -Raw) -join "`n"|ConvertFrom-Json
foreach($i in $Deploy.Deploy.Servers) {
$s=($i | Get-Member -MemberType *property).Name
Write-host "$s" -ForegroundColor Yellow
foreach($j in $s) {
$items=($i.$j|Get-Member -MemberType *property).Name
Write-host "$items" -ForegroundColor Yellow
foreach($k in $items) {
$z=($j.$k | Get-Member -MemberType *property).Name
Write-host "$z" -ForegroundColor Yellow
}
}
}
Current result is :
Webservers
Server site VDIR
Winservers
Server winService
But expected result should be like below:
Webservers:
Server: Sites: VDIR:
list of servers list of sites list of VDIR
Server: Sites: VDIR:
list of servers list of sites list of VDIR
Winservers:
Server: services:
list of servers list of sites
Kindly help ... i'm trying by best in different ways but none of one gave expected result.

OK. I think your problem can be solved with next way.
$ht, $src = #{}, 'D:\sandbox\source.xml'
($srv = (Get-Content $src | ConvertFrom-Json).Deploy.Servers).ForEach{
$name = $_.PSObject.Properties.Name
$ht[$name] = $srv.$name
}
Write-Host Webservers -ForegroundColor Yellow
$ht.Webservers | Out-String
Write-Host Winservers -ForegroundColor Yellow
$ht.Winservers | Out-String

If what you want to achieve is just a formatted output, maybe this is more to your liking
$deploy = Get-Content 'D:\Deploy.json' -Raw | ConvertFrom-Json
Write-Host "Webservers:`r`n-----------"
$items = #()
foreach ($server in $deploy.Deploy.Servers.Webservers) {
foreach ($item in $server) {
$items += New-Object -TypeName PSObject -Property ([ordered]#{
Server = #($item.Server) -join ', '
Sites = #($item.site) -join ', '
VDIR = #($item.VDIR) -join ', '
})
}
}
$items | Out-String
Write-Host "Winservers:`r`n-----------"
$items = #()
foreach ($server in $deploy.Deploy.Servers.Winservers) {
foreach ($item in $server) {
$items += New-Object -TypeName PSObject -Property ([ordered]#{
Server = #($item.Server) -join ', '
WinService = #($item.winService) -join ', '
})
}
}
$items | Out-String
The output will look like this:
Webservers:
-----------
Server Sites VDIR
------ ----- ----
Server1, Server2 website1, WebSite2 WebSite1, WebSite2
Server1, Server2 WebSite1, WebSite2 WebSite1, WebSite2
Winservers:
-----------
Server WinService
------ ----------
Server1, Server2 service1, service2
Server3, Server4 service3, service4

A pragmatic for-display-only solution that doesn't output the exact format you describe, but is concise (PSv3+):
(Get-Content -Raw D:\Deploy.json | ConvertFrom-Json).Deploy.Servers |
ForEach-Object {
$serverTypePropName = $_.psobject.properties.Name
Write-Host "${serverTypePropName}:"
$_.$serverTypePropName | Format-Table
}
(Get-Content -Raw D:\Deploy.json | ConvertFrom-Json) converts the JSON input to custom objects.
.Deploy.Server accesses the array-valued property whose elements are the objects whose Webservers and Winservers properties, respectively, contain the server-details sub-arrays.
In the ForEach-Object script block:
$_.psobject.properties.Name extracts the name of the one property (Webservers or Winservers) of each input object that contains the array of server details.
$_.$serverTypePropName | Format-Table accesses that property and renders the server-details array as a table.
Note that explicit use of Format-Table is needed, because the server-detail arrays have different property structures between the Webservers and the Winservers object; without an explicit formatting/output command, only the first array's properties would render.
With your sample input, the above yields:
Webservers:
Server site VDIR
------ ---- ----
{Server1, Server2} {website1, WebSite2} {WebSite1, WebSite2}
{Server1, Server2} {WebSite1, WebSite2} {WebSite1, WebSite2}
Winservers:
Server winService
------ ----------
{Server1, Server2} {service1, service2}
{Server3, Server4} {service3, service4}

Related

Powershell Parse Swagger Json

The following works to parse a Swagger json into resource, method, httptype but probably... the $path.Definition part is weirdly, how can i get $path.Definition to be an array not a string that i need to parse for the array symbol.
$json = Get-Content -Path "$PSScriptRoot/Test/example_swagger.json" | ConvertFrom-Json
$paths = Get-Member -InputObject $json.paths -MemberType NoteProperty
$result = ""
foreach($path in $paths) {
$elements = $path.Name.Substring(5).split("/") -join ","
$httpmethods = $path.Definition.Substring($path.Definition.IndexOf("#{"))
if ($httpmethods.Contains("get")) {
$result += $elements + ", GET" + "`n"
}
if ($httpmethods.Contains("post")) {
$result += $elements + ", POST" + "`n" #same methodnames different http methods
}
}
$result
As detailed in my answer to Iterating through a JSON file PowerShell, the output of ConvertFrom-Json is hard to iterate over. This makes "for each key in object" and "keys of object not known ahead of time" kinds of situations more difficult to handle, but not impossible.
You need a helper function:
# helper to turn PSCustomObject into a list of key/value pairs
function Get-ObjectMember {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True)]
[PSCustomObject]$obj
)
$obj | Get-Member -MemberType NoteProperty | ForEach-Object {
$key = $_.Name
[PSCustomObject]#{Key = $key; Value = $obj."$key"}
}
}
with this, the approach gets a whole lot simpler:
$swagger = Get-Content -Path "example_swagger.json" -Encoding UTF8 -Raw | ConvertFrom-Json
$swagger.paths | Get-ObjectMember | ForEach-Object {
[pscustomobject]#{
path = $_.Key
methods = $_.Value | Get-ObjectMember | ForEach-Object Key
}
}
Applied to the default Swagger file from https://editor.swagger.io/ as a sample, this is printed
path methods
---- -------
/pet {post, put}
/pet/findByStatus get
/pet/findByTags get
/pet/{petId} {delete, get, post}
/pet/{petId}/uploadImage post
/store/inventory get
/store/order post
/store/order/{orderId} {delete, get}
/user post
/user/createWithArray post
/user/createWithList post
/user/login get
/user/logout get
/user/{username} {delete, get, put}

How to Get the values from json using powershell

Guys this is my JSON file and I want to create a PowerShell script which will give me result like
I have used method like Get-Content and other but there are some issues with the JSON parsing. Please find what is my requirement I have explained in details below.
MyLocalMachineHome
LocalMachine = Sahil_LocalMachine
Second_MyLocalMachine = Sahil_MylocalMachine
Second_MyLocalMachine = ""
Staging
Second_Staging = Sahil;_Secconf
Staging = Sahil_Staging
third_staging = stsajiii
There is also one functionality which I would like to have if I want to get only variables of "staging".
I was using this function Get-Content -Raw -Path E:\shell\Powershell\1ReleasePipelines.json | ConvertFrom-Json | select -ExpandProperty variables on my original JSON file but somehow there is some kind of limit in storing string which I was getting from this method.
{
"environments": [
{
"id": 3,
"name": "MyLocalMachineHome",
"variableGroups": [],
"variables": {
"LocalMachine": {
"value": "Sahil_LocalMachine"
},
"Second_MyLocalMachine": {
"value": "Sahil_MylocalMachine"
},
"thirf_mylocal": {
"value": ""
}
}
},
{
"id": 7,
"name": "Staging",
"variableGroups": [],
"variables": {
"Second_Staging": {
"value": "Sahil;_Secconf"
},
"Staging": {
"value": "Sahil_Staging"
},
"third_staging": {
"value": "stsajiii"
}
}
}
]
}
If we assume that $json contains your JSON content, you can do the following ugly code:
$environment = 'staging'
$j = $json | ConvertFrom-Json
($j.environments | where name -eq $environment).variables | Foreach-Object {
$CurrentObject = $_
$CurrentObject | Get-Member -MemberType NoteProperty |
Select-Object -Expand Name | Foreach-Object {
$CurrentObject.$_.value
}
}
It appears your issue is that you don't know what variables are going to be contained within your JSON. So you can't easily use Select-Object variable or $object.variable. You need a dynamic approach.
If you know your variables ahead of time, things become simpler. You can store your variable names in an array and loop over them.
$variables = 'Second_Staging','Staging','third_staging'
$environment = 'staging'
$j = $json | ConvertFrom-Json
$jsonVars = ($j.environments | where name -eq $environment).variables
$variables | Foreach-Object {
$jsonVars.$_.value
}
View all the sub-properties of variables with format-list instead of format-table. Since the properties vary, format-table won't show all of them. There's a lot of sloppy object construction in json.
$a = get-content file.json
$a.environments.variables | format-table
LocalMachine Second_MyLocalMachine thirf_mylocal
------------ --------------------- -------------
#{value=Sahil_LocalMachine} #{value=Sahil_MylocalMachine} #{value=}
$a.environments.variables | format-list
LocalMachine : #{value=Sahil_LocalMachine}
Second_MyLocalMachine : #{value=Sahil_MylocalMachine}
thirf_mylocal : #{value=}
Second_Staging : #{value=Sahil;_Secconf}
Staging : #{value=Sahil_Staging}
third_staging : #{value=stsajiii}
Get the staging variables?
$a.environments | where name -eq staging | foreach variables
Second_Staging Staging third_staging
-------------- ------- -------------
#{value=Sahil;_Secconf} #{value=Sahil_Staging} #{value=stsajiii}
cls
start-transcript -path 'C:\E\Devops\PowerShell_Chapters\ABC.txt'
write-output "**********Variables of Release************"
get-content -raw -path 'C:\E\Devops\PowerShell_Chapters\Release.json'| Convertfrom-Json | Select -ExpandProperty variables
$json = get-content -raw -path 'C:\E\Devops\PowerShell_Chapters\Release.json'| Convertfrom-Json | Select -ExpandProperty environments
$EnvirnomentsVariables = get-content -raw -path 'C:\E\Devops\PowerShell_Chapters\Release.json'| Convertfrom-Json | Select -ExpandProperty environments |Select -ExpandProperty name
$ReleaseVariable = get-content -raw -path 'C:\E\Devops\PowerShell_Chapters\Release.json'| Convertfrom-Json | Select -ExpandProperty environments |Select -ExpandProperty variables
$i = 0
foreach($a in $EnvirnomentsVariables)
{
$ABC_Staging = $EnvirnomentsVariables[$i]
#write-output $ABC_Staging
if( $ABC_Staging -match "ABC Staging")
{
write-output "****************Variables of " $EnvirnomentsVariables[$i]*************"
#add-content 'C:\E\Devops\PowerShell_Chapters\ABC.txt' $EnvirnomentsVariables[$i]
# Set-content -path 'C:\E\Devops\PowerShell_Chapters\Sahil.json'| ConvertTo-Json | select $EnvirnomentsVariables[$i]
write-output $ReleaseVariable[$i]
# add-content 'C:\E\Devops\PowerShell_Chapters\ABC.txt' $ReleaseVariable[$i]
# Set-content -path 'C:\E\Devops\PowerShell_Chapters\Sahil.json'| ConvertTo-Json | select $ReleaseVariable[$i]
}
$i = $i + 1
}
stop-transcript

Serialize JSON from Powershell in a specific fashion

So I have this script that goes out and finds all the software versions installed on machines and lets people know what software and when it was installed across several VMs.
I want to put this on a Dashboard provider we use but they have a specific format in which to use it.
it does produce a valid JSON however I just found out it's not in the format the company wishes.
which would be:
{"table": [["header1", "header2"], ["row1column1", "row1column2"], ["row2column1", "row2column2"]]}
My first thought would be to produce a header row as a beginning variable and then individual variables for each component but that feels very tedious and laborious to create variables for each individual row of data (Date, Name of Software, etc). then at the end combine them into 1 and convert to json
My script is this:
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline = $true,
ValueFromPipelinebyPropertyName = $true)]
[Alias("Servers")]
[string[]]$Name = (Get-Content "c:\utils\servers.txt")
)
Begin {
}
Process {
$AllComputers = #()
#Gather all computer names before processing
ForEach ($Computer in $Name) {
$AllComputers += $Computer
}
}
End {
ForEach ($Computer in $AllComputers) {
write-output "Checking $computer"
if ($computer -like "*x86*") {
$data = Invoke-Command -cn $computer -ScriptBlock {Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object #{Label = "ServerName"; Expression = {$env:computername}}, DisplayName, Publisher, DisplayVersion, InstallDate | Where-object { $_.Publisher -match "Foobar" }}
$jsondata += $data
}
else {
$data = Invoke-Command -cn $computer -ScriptBlock { Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object #{Label = "ServerName"; Expression = {$env:computername}}, DisplayName, Publisher, DisplayVersion, InstallDate | Where-object { $_.Publisher -match "foobar" } }
$jsondata += $data
}
}
$jsondata | ConvertTo-Json -depth 100 | Out-File "\\servername\C$\Utils\InstalledApps.json"
}
From the sample output format provided I would conclude that you are looking for an array of array. There is a "bug" using ConvertTo-Json when trying to do this but since we need it inside a table object anyway. I will show an example using your code but just on my local computer. Integrating this into your code should not be an issue.
# gather the results
$results = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-object { $_.Publisher -match "The" } | Select-Object #{Label = "ServerName"; Expression = {$env:computername}}, DisplayName, Publisher, DisplayVersion, InstallDate
# Prepare an array of arrays for the output.
$outputToBeConverted = #()
# build the header
$header = ($results | Get-Member -MemberType NoteProperty).Name
$outputToBeConverted += ,$header
# Add the rows
Foreach($item in $results){
# Create a string array by calling each property individually
$outputToBeConverted += ,[string[]]($header | ForEach-Object{$item."$_"})
}
[pscustomobject]#{table=$outputToBeConverted} | ConvertTo-Json -Depth 5
Basically it is making a jagged array of arrays where the first member is your "header" and each row is built manually from the items in the $results collection.
You will see the unary operator , used above. That is done to prevent PowerShell from unrolling the array. Without that you could end up with one long array in the output.

Access Object From JSON File in Powershell

I have a JSON file that I am reading in Powershell. The structure of the file is below.
[
["computer1", ["program1", versionX]],
["computer2", ["program2", versionY]],
["computer3", ["program3", "versionX"],
["program1", "versionZ"]
],
]
What I want in the program is use $env:computername and compare it with the computerX in the JSON file. If found a match, then iterate through and get the values of programName and ProgramVersion.
However, I don't know how to search through the objects and find ALL items under that.
This is what I have so far.
$rawData = Get-Content -Raw -Path "file.json" | ConvertFrom-Json
$computername=$env:computername
$data = $rawData -match $computername
This gives me objects under it. But how do I iterate through and get individual values?
But don't know what I do after that.
To start you need to be using a valid JSON file
{
"computer1": {
"program1": "versionX"
},
"computer2": {
"program2": "versionY"
},
"computer3": {
"program3": "versionX",
"program1": "versionZ"
}
}
Then you can access the PSObject Properties
$rawData = Get-Content -Raw -Path "file.json" | ConvertFrom-Json
$rawData.PsObject.Properties |
Select-Object -ExpandProperty Name |
ForEach-Object { IF ($_ -eq $env:COMPUTERNAME) {
Write-Host "Computer Name : " $_
Write-Host "Value : " $rawData."$_"
}
}
EDIT for Computer, Program, and Version as separate values
psobject.Properties.Name will give all the program names.
psobject.Properties.Name[0] will give the first program name.
psobject.Properties.value[0] will give the first program version value.
You need to increment the value to get second value, you can also use -1 as a shortcut for the last value.
$rawData = Get-Content -Raw -Path "file.json" | ConvertFrom-Json
$rawData.PsObject.Properties |
Select-Object -ExpandProperty Name |
ForEach-Object { IF ($_ -eq $env:COMPUTERNAME) {
$Computer = $_
$Values = $rawData.$_
}
}
$Computer
$Values.psobject.Properties
$Values.psobject.Properties.Name
$Values.psobject.Properties.Name[0]
$Values.psobject.Properties.value[0]
$Values.psobject.Properties.Name[1]
$Values.psobject.Properties.value[1]
You could also use the program name
$Values.program1
$Values.program2
$Values.program3

Hashtables from ConvertFrom-json have different type from powershells built-in hashtables, how do I make them the same?

I have a json file (test.json) that looks something like this:
{
"root":
{
"key":"value"
}
}
I'm loading it into powershell using something like this:
PS > $data = [System.String]::Join("", [System.IO.File]::ReadAllLines("test.json")) | ConvertFrom-Json
root
----
#{key=value}
I'd like to be able to enumerate the keys of the 'hashtable' like object that is defined by the json file. So, Ideally, I'd like to be able to do something like:
$data.root.Keys
and get ["key"] back. I can do this with the built-in hashtables in powershell, but doing this with a hashtable loaded from json is less obvious.
In troubleshooting this, I've noticed that the fields returned by ConvertFrom-json have different types than those of Powershell's hashtables. For example, calling .GetType() on a built-in hashtable makes shows that it's of type 'Hashtable':
PS > $h = #{"a"=1;"b"=2;"c"=3}
PS > $h.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Hashtable System.Object
doing the same for my json object yields PSCustomObject:
PS > $data.root.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False PSCustomObject System.Object
Is there any way to cast or transform this object into a typical powershell Hashtable?
Here's a quick function to convert a PSObject back into a hashtable (with support for nested objects; intended for use with DSC ConfigurationData, but can be used wherever you need it).
function ConvertPSObjectToHashtable
{
param (
[Parameter(ValueFromPipeline)]
$InputObject
)
process
{
if ($null -eq $InputObject) { return $null }
if ($InputObject -is [System.Collections.IEnumerable] -and $InputObject -isnot [string])
{
$collection = #(
foreach ($object in $InputObject) { ConvertPSObjectToHashtable $object }
)
Write-Output -NoEnumerate $collection
}
elseif ($InputObject -is [psobject])
{
$hash = #{}
foreach ($property in $InputObject.PSObject.Properties)
{
$hash[$property.Name] = ConvertPSObjectToHashtable $property.Value
}
$hash
}
else
{
$InputObject
}
}
}
The ConvertFrom-Json cmdlet gives you a custom object so you have to access them using dot notation rather than as a subscript. Usually you would know what fields you expect in the JSON so this is actually more useful in general than getting a hash table. Rather than fighting the system by converting back to a hash table, I suggest you work with it.
You can use select with wildcard property names to get at the properties:
PS D:\> $data = #"
{
"root":
{
"key":"value", "key2":"value2", "another":42
}
}
"# | ConvertFrom-Json
PS D:\> $data.root | select * | ft -AutoSize
key key2 another
--- ---- -------
value value2 42
PS D:\> $data.root | select k* | ft -AutoSize
key key2
--- ----
value value2
and Get-Member if you want to extract a list of property names that you can iterate over:
PS D:\> ($data.root | Get-Member -MemberType NoteProperty).Name
another
key
key2
Putting that into a loop gives code like this:
PS D:\> foreach ($k in ($data.root | Get-Member k* -MemberType NoteProperty).Name) {
Write-Output "$k = $($data.root.$k)"
}
key = value
key2 = value2
The example was for a relatively shallow source object (not nested objects in the properties).
Here's a version that will go 2 levels deep into the source object, and should work with your data:
$data = #{}
foreach ($propL1 in $x.psobject.properties.name)
{
$data[$propL1] = #{}
foreach ($propL2 in $x.$propL1.psobject.properties.name)
{
$data[$PropL1][$PropL2] = $x.$propL1.$propL2
}
}
$data.root.keys
key
I put this together to handle nested json to hashtables
function ConvertJSONToHash{
param(
$root
)
$hash = #{}
$keys = $root | gm -MemberType NoteProperty | select -exp Name
$keys | %{
$key=$_
$obj=$root.$($_)
if($obj -match "#{")
{
$nesthash=ConvertJSONToHash $obj
$hash.add($key,$nesthash)
}
else
{
$hash.add($key,$obj)
}
}
return $hash
}
I have only tested with 4 levels but recursive until it has complete hashtable.
#Duncan: If you need to use JSON Input for an command expecting a hashmap though (eg SET-ADUSER), try something like this:
function SetADProperties{
param($PlannedChanges)
$UserName = $PlannedChanges.Request.User
$Properties = #{}
foreach ($key in ($PlannedChanges.SetADProperties | Get-Member -MemberType NoteProperty).Name)
{
$Properties[$key] = $PlannedChanges.SetADProperties.$key
}
# Call Set-ADUser only once, not in a loop
Set-ADUser -Identity $UserName -Replace $Properties
}
$content = Get-Content -encoding UTF8 $FileName
$PlannedChanges = $content | ConvertFrom-Json
SetADProperties $PlannedChanges | Write-Output
Example JSON:
{"SetADProperties":{"postalCode":"01234","l":"Duckburg","employeenumber":"012345678"},
"Request":{"Action":"UserMove","User":"WICHKIND","Change":"CH1506-00023"}}