Home > OS >  replace string with varying content using powershell
replace string with varying content using powershell

Time:07-10

I have a set of folders in which there are some json files. I am trying to write a powershell script to convert the below line for all the json in the folder:

"objectStatus": "ACTIVE",

The above line from json files can differ with more than one space between the key and value:

"objectStatus":     "ACTIVE",

The script that I wrote is:

$jsonFiles = Get-ChildItem . *.json -rec
foreach ($file in $jsonFiles)
{
    (Get-Content $file.PSPath) |
    Foreach-Object {$_ -replace '"ACTIVE"','"INACTIVE"'} |
    Set-Content $file.PSPath
}

You can see that the above replaces the string '"ACTIVE"' to '"INACTIVE"'. However, I want to replace the '"ACTIVE"' string only when the key is "objectStatus". Also, there can be more than one space between the key and value. How can I handle that while replacing the string?

Thanks in advance!

CodePudding user response:

You can make search by full string like this. '"objectStatus":\s*"ACTIVE"','"objectStatus": "INACTIVE"'

$jsonFiles = Get-ChildItem . *.json -rec
foreach ($file in $jsonFiles)
{
    (Get-Content $file.PSPath) |
    Foreach-Object {$_ -replace '"objectStatus":\s*"ACTIVE"','"objectStatus": "INACTIVE"'} |
    Set-Content $file.PSPath
}

  • Related