Get value from json variable using windows powershell 5.1 - powershell

I've got a JSON like this
[
{
"Param1":true,
"Param2":0,
"Param3":"OK"
...
...
}
]
How can I get Param2 value, using powershell 5.1?
For now, I tried to get property names, but only get length
$jsondeconverted = $jsonOrig | ConvertFrom-Json
$jsonOrig .PsObject.Properties |
Select-Object -ExpandProperty Name |
ForEach-Object {
Write-Host "Key : " $_
Write-Host "Value : " $thisJSON."$_"
}
EDIT
This is how I get my json
$jsonvar = '['+$jsonvar+']'
$convertedJson = $jsonvar | ConvertTo-Json -Depth 10
$deconvertedJson = $convertedJson | ConvertFrom-Json
$deconvertedJson contains only length parameter and nothing more.

You need to look into the object ($jsondeconverted) rather than the string ($jsonOrig)
Based on your json Structure, you would access param2 in the following way $jsondeconverted[0].Param2
Verifiable complete example
$jsonorig = '[{"Param1":true,"Param2":0,"Param3":"OK"}]'
$jsondeconverted = $jsonorig | ConvertFrom-Json
$jsondeconverted[0].param2

Related

How to get child dynamically with name in power shell

wanted to traverse in json body and get values from list using powershell.
json file
{   
 "TopicPropProfiles": [    
{        
"TP1":{            
"enable-duplicate-detection": true,            
"enable-batched-operations": true,            
"enable-ordering": true      
},        
"TP2":{            
"max-delivery-count": 3,            
"enable-batched-operations": true      
}    
}    
],    
"SubPropProfiles": [    
{        
"SP1":{            
"enable-duplicate-detection": true,                        
"max-size": 1024        
},        
"SP2":{            
"max-delivery-count": 3,            
"enable-batched-operations": true,                       
"enable-session": false                  
}    
}    
],    
"Topics":[    
{        
"TopicName": "topic1",        
"SubNames": ["sub1","sub2","sub3"],        
"TopicPropertyProfile": "TP1",        
"SubPropertyProfile": "SP2" 
},    
{        
"TopicName": "topic2",        
"SubNames": ["sub4","sub5","sub6"],        
"TopicPropertyProfile": "TP2",        
"SubPropertyProfile": "SP1"    
}
]
}
powershell --getting file from somepath($profilepath)
$profilejson = Get-Content -Raw $profilePath | ConvertFrom-Json;
$profileObject = [PSCustomObject]$profilejson;
$TopicProps=$profileObject.TopicPropProfiles.**TP1**;
Write-Host $TopicProps.'enable-duplicate-detection'
Wanted to get fields values under TP1 or TP2(this value will be passed dynamically through some other parameters). Is above syntax/approach correct?
I have reproduced in my environment and I got expected results as below:
$result = Get-Content "Path" -raw | ConvertFrom-Json
$result.TopicPropProfiles.TP1
what if TP1 if also in some var like $profile=TP1 then?
$result = Get-Content "path" -raw | ConvertFrom-Json
$profile='TP1'
$result.TopicPropProfiles[0].$profile
To get the values of specific keys, you can use the dot notation. Example :
$json = Get-Content -Raw .\json.json | ConvertFrom-Json
$json.TopicPropProfiles
To see the content of TP1
$json.TopicPropProfiles.TP1
To get get the value of your first key/value pair inside TP1
$json.TopicPropProfiles.TP1.'enable-batched-operations'
Like this, you'll get the object returned. If you want the values, you need to use Select-Object
$json.TopicPropProfiles.TP1 |Select-Object -ExpandProperty TP1

Getting string from what appears to be a hash-map in PowerShell

In PowerShell, I do this command:
$w = iwr -usedefaultcredentials -uri http://acme.corp/anvils.aspx -method 'POST' -Body '{"ctl00_MainEntityNumber:"Wiley"}'
That returns an object, part of which is an object called InputFiles, one of which is an object called __VIEWSTATE. I want to get the string value of __VIEWSTATE. So I do this:
$f = $w.inputfields | where id -eq __VIEWSTATE | select-object value | select-string value
which gives me a MatchInfo object. If I just print out the object, I get
#{value=/wEPDwUJODU5MDM5MTc0DxYEHhBQYWdlRW50aXR5TnVtYmVyZh4Yb0luc3VyYW5jZVNlYXJjaENyaXRlcmlhMv0BAAEAAAD/////AQAAAAAAAAAMAgAAAFFJRE9JLlJlZ3VsYXRlZEV ....}
which looks to me like a Hashmap or something. But when I try $f.value or $f['value'] I get nothing, or if I $f[0], I get the whole thing (including the #{value=.. part) So the question is, how do I get just the string after the #{value=\ ? Do I have to parse it out manually?
If you're just wanting the value itself then change it to
$f = $w.inputfields | where id -eq __VIEWSTATE | Select-Object -ExpandProperty value

PowerShell export multiple objects as csv

I have two columns of data the first is a string array the second is actually an object. I am looking for a simple way of exporting this as a csv. I have a version with a foreach loop that builds each string up but it seams like over kill. I have been trying to use select and select object to get it out somehow. Note I am just a beginner at powershell so I may be missing something.
My first attempt:
$data | Select-Object -ExpandProperty reports | Select -ExpandProperty data | Select -ExpandProperty rows | Format-Table $_.dimensions
Results in:
dimensions metrics
---------- -------
{New Visitor, "Mozilla} {#{values=System.Object[]}}
My second one went as far as looping
foreach ($report in $data.reports) {
"Rows:" + $report.data.rows.Count
foreach ($row in $report.data.rows) {
$output = ""
foreach($dim in $row.dimensions) {
$output += $dim + $seporator
}
foreach($met in $row.metrics) {
foreach($v in $met.values) {
$output += $v + $seporator
}
}
#| Out-File -Append C:\Users\linda_l\Documents\debug.txt
$output
}
}
There is a potential for a lot of data here so I would really like to avoid the string building solution.
Note: Data comes from the Google Analytics reporting api
$data = Invoke-RestMethod -ContentType 'application/json' -Uri "https://analyticsreporting.googleapis.com/v4/reports:batchGet?access_token=$($token.access_token)" -Method POST -Body $analyticsRequest
reports : {#{columnHeader=; data=}}
From comment:
$data | Export-Csv -Path "C:\Users\linda_l\Documents\debug2.csv"
System.Management.Automation.PSCustomObject reports System.Object[]
Optimal output csv
New Visitor,S40 Ovi Browser,1,2
New Visitor,Safari,3,4
Note its up on Github steps for getting a refreshtoken
Data is coming from the Google analytics reporting API

How to search for a key and change the value of that?

sample.txt:
{"ip":"","port":0,"protocol":"udp","user":false,"test":false}
I want change the 'value' to a particular 'key' in the above dictionary.
For example: For 'port': I need to change '23', for 'protocol', I need to change 'tcp' etc. using Windows PowerShell.
Since you are working with JSON, lets use JSON!
$json = Get-Content .\sample.txt | ConvertFrom-Json
$json.port = 23
$json.protocol = 'tcp'
$json | ConvertTo-Json -Compress | Out-File .\sample.txt
First I read the file and lets powershell convert it from JSON to an object. (Line 1)
I can now edit this object. (Line 2-3)
Finally I convert it back to JSON and write it to the file. (Line 4)
Hope this helps.
Your sample data appears to be in JSON format, so you'd modify it by converting the JSON string to an object, change the properties, then convert the object back to a JSON string, like this:
$file = 'C:\path\to\sample.txt'
(Get-Content $file -Raw) | ConvertFrom-Json | ForEach-Object {
$_.port = 23
$_.protocol = 'tcp'
$_ # echo current object to feed it back into the pipeline
} | ConvertTo-Json -Compress | Set-Content $file
On PowerShell v2 or earlier you need to run (Get-Content $file) | Out-String to emulate the parameter -Raw that was introduced with v3.

How to get the value of a particular propery from the result of a powershell command

I have a variable $ results which has the value :
SESSIONNAME USERNAME ID STATE TYPE DEVICE
rdp-tcp#1 account17 7 Active rdpwd
I want to get the value of ID alone and use it in a different query.
I tried the following ways :
1.$idValue = #($result | %{ $_.ID }) - but it was not getting the value.
2.$result |Select -ExpandProperty ID - I was getting the error 'Select-Object : Property "ID" cannot be found.'
How to get the value of the property ID alone from the result?
The output of the qwinsta/query commands are strings, not objects, so there isn't a property ID to print. You need to transform the strings into objects if you want the fields as properties:
query session | ? { $_ -match '^[ >](\S+) +(\S*?) +(\d+) +(\S+)' } |
select #{n='Service';e={$matches[1]}},
#{n='Username';e={$matches[2]}},
#{n='ID';e={$matches[3]}},
#{n='Status';e={$matches[4]}} | % {
$_.ID
}
Or, if you're just interested in the ID, you could do a regular expression replacement like this:
$account = 'account17'
$pattern = '^[ >]\S+ +\S*? +(\d+) +\S+.*'
(query session $account | select -Skip 1) -replace $pattern, '$1'
This is the format to refer to a single property properly. I don't see your command to create your RDP $result, so I'll example get-process, encapsulate it with () and tack an ().ID to the end. Works with any property, not just.ID
(get-process | where {$_.Name -eq "Powershell"}|select ID).ID
# or
$MYID = (get-process | where {$_.Name -eq "Powershell"}|select ID).ID
$MYID
Another option is -split:
One solution, using V4:
($result).ForEach({($_ -split '\s+')[2]}) -match '\d'