Powershell: Update one value in Powershell script

Created on 19 May 2018  路  8Comments  路  Source: PowerShell/PowerShell

Consider this json file:
{
"ABC": {
"name": "abc",
"age": "25",
"place": "India"
},
"DEF": {
"name": "def",
"age": "35",
"place": "China"
}
}

I have to run a script that updates "place" value with "USA" for all objects. Final result has to be like this:

{
"ABC": {
"name": "abc",
"age": "25",
"place": "USA"
},
"DEF": {
"name": "def",
"age": "35",
"place": "USA"
}
}

Please let me know if you have any suggestions on the same. Thanks!

Issue-Question Resolution-Answered

All 8 comments

Do you have all your json files in one folder/directory?

I have a json file. I'm calling this json file in a powershell script. Both are in same folder.

function Set-Country {
    [cmdletbinding()]
    param(
        [String]$newPlace = '"place": "USA"'
    )

    begin {
        Write-Verbose -Message "Starting Set-Country..."
        $VerbosePreference = 'Continue'
        $filesToCheck = Get-ChildItem -Path .\ -Filter *.json
        Set-Location -Path .\
    }

    process {
        try {
            #replace place with "USA"
            foreach ($file in $filesToCheck) {
                Write-Verbose -Message "Replacing 'Place' in $file."
                (Get-Content $file.Name) -replace ('"place"\:."([^"]*)"'), $newPlace | 
                    Out-File -Filepath $file.Name -Verbose
            }
        }
        catch {
            Write-Verbose -Message $_.Exception | Format-List -Force
        }
    }

    end {
        If($?){
            Write-Verbose -Message "Completed Succesfully..."
          }
    }
}

here you go

Thank you so much! if I have a comma at the end of the line:
"place": "USA",
how do I make sure it won't get replaced?

updated

Thank you so much! Really appreciate your help!

."([^"]*)"' didn't work. It still replaces the comma.

An alternative approach would be to manipulate the JSON objects instead of the file text. The following code will read the file into a JSON object, update the properties, then save the updated JSON back to the file:

$jdata = Get-Content -Raw "file.json" | ConvertFrom-Json
foreach ($p in $jdata.PSObject.Properties)
{
    $p.Value.place = "USA"
}
$jdata | ConvertTo-Json | Set-Content "file.json"
Was this page helpful?
0 / 5 - 0 ratings