(Powershell) Read and change JSON value to a date - json

I'm trying to write a powershell script that could read a JSON, its extension is .pros, then change the project name from "test" to "test 12/12 13:24" or something similar. So far I was able to read it, but then I can't get to the project_name field.
my code:
$pros = Get-ChildItem -Path $house -Recurse -Include *.pros
$time = Get-Date -Format 'u'
$pog = Get-Content $pros -raw | ConvertFrom-Json
$pog.update | $_.project_name=$time
$pog | ConvertTo-Json -depth 32| set-content $pros
Write-Output $time
The .pros:
{
"py/object": "pros.conductor.project.Project",
"py/state": {
"project_name": "Marcos_Yuck_new",
"target": "v5",
"templates": {
"kernel": {
"location": "/home/dragon/.config/pros/templates/kernel#3.5.3",
"metadata": {

Related

Ignoring files in Get-ChildItem from objects being loaded from JSON

I have a script that I am using to read a JSON file, read the paths, calculate the MD5 hash and then export them in a CSV file. The JSON file contains multiple objects. In another post, I laid out the structure of the JSON file and I'll post that here. Please note that I am not allowed to change this JSON.
{
"destinationpath": "C:\\Destination\\Mobile Phones\\"
"sourcepath": "C:\\Source\\Mobile Phones\\"
"OnePlus" : {
"files": [
{
"source": "6T",
"destination": "Model\\6T",
"log": "logfiles",
"version": "Version.txt",
}
]
}
"Samsung" : {
"files": [
{
"source": "S20",
"destination": "Galaxy\\S20",
"log": "logfiles",
"version": "Version.txt",
}
]
}
}
The destinationpath: C:\\Destination\\Mobile Phones\\, when added to, for example, Samsung it becomes: destinationpath: C:\\Destination\\Mobile Phones\\Galaxy\\S20.
The script that I have so far is this:
$JSON = Get-Content -Path file.json | ConvertFrom-Json
$JSONdestination = $JSON.destination
$JSONsource = $JSON.source
foreach ($i in $JSON.psobject.properties) {
foreach($i2 in $i.Value ){
$IgnoredFiles = #(
$logfiles = $i2.files.log
$newFiles = $i2.files.version
)
$destination = $JSON + $i2.files.destination
$source = $JSONdestination + $i2.files.source
echo $destination
Get-ChildItem -Path $destination -Recurse -Exclude $IgnoredFiles | Get-FileHash -Algorithm MD5 -ErrorAction SilentlyContinue | Export-csv -Append -Path "C:\Users\home\Downloads\hashes.csv"
}
In the Get-ChildItem portion, I want to exclude the "log" and "version" files so that they are not counted in the Get-FileHash. I have tried doing it this way as well:
Get-ChildItem -Path $destination -Recurse -Exclude $i2.files.log, $i2.files.version | Get-FileHash -Algorithm MD5 -ErrorAction SilentlyContinue | Export-csv -Append -Path "C:\Users\home\Downloads\hashes.csv"
However, it doesn't work either and the log and version files are still taken into account in the exported csv.
The json you show us is invalid (missing commas and commas too many..)
Once fixed into
{
"destinationpath": "C:\\Destination\\Mobile Phones\\",
"sourcepath": "C:\\Source\\Mobile Phones\\",
"OnePlus": {
"files": [{
"source": "6T",
"destination": "Model\\6T",
"log": "*.log",
"version": "Version.txt"
}]
},
"Samsung": {
"files": [{
"source": "S20",
"destination": "Galaxy\\S20",
"log": "*.log",
"version": "Version.txt"
}]
}
}
you can do this:
$JSON = Get-Content -Path file.json | ConvertFrom-Json
$JSONdestination = $JSON.destinationpath
$JSONsource = $JSON.sourcepath
$result = foreach ($item in ($JSON | Select-Object * -ExcludeProperty destinationpath, sourcepath)) {
$item.PSObject.Properties.Value | ForEach-Object {
$destPath = Join-Path -Path $JSONdestination -ChildPath $_.files.destination
$logFolder = Join-Path -Path $JSONdestination -ChildPath $_.files.log
$exclude = $_.files.version
Write-Host "Processing files in '$destPath'" -ForegroundColor Cyan
Get-ChildItem -Path $destPath -Recurse -Exclude $exclude -ErrorAction SilentlyContinue |
Where-Object {$_.FullName -notlike "$logFolder*" } |
Get-FileHash -Algorithm MD5
}
}
$result | Export-Csv -Path "C:\Users\home\Downloads\hashes.csv" -NoTypeInformation

Manipulate JSON File with multiple objects using Powershell

I have a JSON File called index.json which looks like this :
{
"First": {
"href": "test/one two three.html",
"title": "title one"
},
"Second": {
"href": "test/test test/one two three four.html",
"title": "title two"
}
}
I want to write a powershell script to update the href of each object to replace the spaces with -.
The JSON file should looks like this:
{
"First": {
"href": "test/one-two-three.html",
"title": "title one"
},
"Second": {
"href": "test/test-test/one-two-three-four.html",
"title": "title two"
}
}
I got some help from this post:
Iterating through a JSON file PowerShell
I have already written a script to get all the href values, I dont know how to update the same in the original JSON file. My script looks like this:
function Get-ObjectMembers {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True)]
[PSCustomObject]$obj
)
$obj | Get-Member -MemberType NoteProperty | ForEach-Object {
$key = $_.Name
[PSCustomObject]#{Key = $key; Value = $obj."$key"}
}
}
$a = Get-Content 'index.json' -raw | ConvertFrom-Json | Get-ObjectMembers
foreach($i in $a){
$i.Value.href.Replace(" ","-")
}
I've done it this way.
$path='index.json'
$Content= (Get-Content $path -raw | ConvertFrom-Json)
$memberNames=( $Content | Get-Member -MemberType NoteProperty).Name
foreach($memberName in $memberNames){
($Content.$memberName.href)=($Content.$memberName.href).Replace(" ","-")
}
$Content | ConvertTo-Json | Out-File $path -Append

Read one Value of a specific object from a json file

I want to return only the hash value of one object from my test.json file.
Right now, I am getting all hash values with my code.
json file:
[
{
"name": "abc.txt",
"hash": "D23FC7C4C9F1ED7CD147D7D29E3A541D"
},
{
"name": "def.txt",
"hash": "681B75B81734F7215C2DAD1F7EDFDAF7"
},
{
"name": "ghi.txt",
"hash": "81709CDC04EBDBDAA9BA15F6CAF1F05B"
},
{
"name": "xyz.txt",
"hash": "56F07815D06966FA3A73275797496881"
}
]
My code:
$jsonFile = $PSScriptRoot + "\test.json"
(Get-Content $jsonFile | ConvertFrom-Json | where {$_.name -eq 'abc.txt'}).hash
Careful with the parentheses:
((Get-Content $jsonFile | ConvertFrom-Json) | where {$_.name -eq "abc.txt"}).hash
#D23FC7C4C9F1ED7CD147D7D29E3A541D
Like this your json file contains a list of dictionaries. First you need to select which item of your list you want to have and then you can retrieve the value based on the key.
Try something like this:
$jsonFile = $PSScriptRoot + "\test.json"
$jsonList = Get-Content $jsonFile | ConvertFrom-Json
$jsonList[0].hash
Alternatively:
$jsonObject = $jsonList | Where-Object {$_.name -eq 'abc.txt'} | Select-Object hash

Unable to copy json block

I'm trying to copy condition block from id 106 to id 107 with script below; however, I got error "ConvertFrom-Json : Invalid JSON primitive:". Am I missing something? Please advise.
$a = Get-Content 'C:\DevOps\mytest.json' -raw | ConvertFrom-Json
$condition = $a | select -expand environments | select -expand conditions
Write-Host $condition[0]
$a | add-member -Name $condition[1].name -value (Convertfrom-Json $condition[0]) -MemberType NoteProperty
Write-Host $update
$a | ConvertTo-Json -Depth 20 | set content 'C:\DevOps\updatedmytest.json'
The JSON file contains:
{
"source": "userInterface",
"id": 25,
"revision": 3,
"environments": [
{
"id": 106,
"conditions": [
{
"name": "ReleaseStarted",
"conditionType": "event",
"value": ""
}
]
},
{
"id": 107,
"conditions": [
]
}
]
}
Best Regards,
Andy Pham
The error message you are receiving is because you convert the JSON into a PowerShell Object and then saved it into the variable $a. $condition then is still a PowerShell object that you have expanded and is not JSON. So -value (Convertfrom-Json $condition[0]) doesn't work because it's already converted.
Convert to an object, make changes directly to the object, convert from the object.
$ConvertedJSON = Get-Content 'C:\DevOps\mytest.json' -Raw | ConvertFrom-Json
$ConvertedJSON.environments[1].conditions = $ConvertedJSON.environments[0].conditions
$ConvertedJSON | ConvertTo-Json -Depth 20 | Set-Content 'C:\DevOps\updatedmytest.json'
Alternatively, you could use Where-Object to filter for the ids.
$ConvertedJSON = Get-Content 'C:\DevOps\mytest.json' -Raw | ConvertFrom-Json
($ConvertedJSON.environments | Where-Object {$_.id -eq 107}).conditions = ($ConvertedJSON.environments | Where-Object {$_.id -eq 106}).conditions
$ConvertedJSON | ConvertTo-Json -Depth 20 | Set-Content 'C:\DevOps\updatedmytest.json'

How do I update JSON file using PowerShell

I have one json file mytest.json like below I want to update values using PowerShell script
update.json
{
"update": [
{
"Name": "test1",
"Version": "2.1"
},
{
"Name": "test2",
"Version": "2.1"
}
]
}
I want to write a PowerShell script where if Name=="test1" I want to update Version= "3"
How can i do it using parameters?
Here is a way :
$a = Get-Content 'D:\temp\mytest.json' -raw | ConvertFrom-Json
$a.update | % {if($_.name -eq 'test1'){$_.version=3.0}}
$a | ConvertTo-Json -depth 32| set-content 'D:\temp\mytestBis.json'
According to #FLGMwt and #mikemaccana I improve the ConvertTo-Json with -depth 32 because the default depth value is 2 and for object deeper than 2 you will receive class informations in spite of objects.
I have also faced the same kind of issue. I was looking to change the records of the below JSON file
{
"SQS_QUEUE_URL": "https://que-url.com/server1",
"SQS_EVENTS_QUEUE_URL": "https://events-server.com/server1/development_events",
"REGION": "region1",
"BUCKET": "test-bucket",
"AE_WORK_PATH": "C:\\workpath\\path1",
"ENV": "env"
}
Finally, I managed to find the easiest way to generate a JSON file from Powershell.
$json = Get-Content "c:\users\bharat.gadade\desktop\test.json" | ConvertFrom-Json
$json.SQS_QUEUE_URL = "https://que-url.com/server2"
$json.SQS_EVENTS_QUEUE_URL = "https://events-server.com/Server2/development_events"
$json.REGION = "region1 "
$json.BUCKET = "test-bucket"
$json.AE_WORK_PATH = "C:\workpath\path1"
$json.ENV = "env"
$json | ConvertTo-Json | Out-File "c:\users\bharat.gadade\desktop\test.json"