Search code examples
jsonpowershellpowershell-4.0powershell-5.0

How to update the value of a property in a json file using the PowerShell?


I am stuck at one of the point in my PowerShell script where I need to update some part of the value for the property named restServiceURL and microServiceURL from http to https. (screenshot below)

json file

I have the below script but somehow I am unable to figure out what needs to be added in order to replace the specific part of the value (http in this case) of the property from "http://VWMAIMPKG16SN/IMatchREST/" to "https://VWMAIMPKG16SN/IMatchREST/"

I know that set-content command should be able to do this but how to do I do it without changing the other part of the value is where I am stuck at.

Any suggestion on this would be helpful.

# Code to get Installation Directory path
$CommonNode=Get-ItemProperty -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\AquagardePI\STeP\Platform\Common
$InstallationDir=$CommonNode.InstallationDir

#Path of Json File
$ConfigPath = $InstallationDir + "Web Client\www\\NextGen\assets\config.json"

#Get Content of the File
$file = Get-Content $ConfigPath -raw | ConvertFrom-Json

#Get the value of Property
$file = $file.restServiceURL

Solution

  • You can first get the JSON object, and then simply replace http with https for the two properties you are interested in:

    $ConfigPath = $InstallationDir + "Web Client\www\\NextGen\assets\config.json"
    $file = Get-Content $ConfigPath -raw | ConvertFrom-Json
    
    $file.microServiceURL = $file.microServiceURL.Replace('http','https')
    $file.restServiceURL = $file.restServiceURL.Replace('http','https')
    
    Set-Content -Value ($file | ConvertTo-Json) -Path $ConfigPath