Hi, I have below script which will look for all the .json files in a specific directory and replaces all words/tokens which begin and end with # symbol (example: #Environment_test1# will be replaced by the value “testvalue1”). But this script is not working as expected, it is replacing only few tokens and ignoring other tokens. When i debugged it i found that the line “$array_list = $token_name[$num -1]” in below script is not returning all values. Please help me to fix this issue.
the .json file contains line like below (it is a single line, not multiple lines) in which the tokens needs to be replaced:
“CsConfiguration”: “{"config": {"baseUrls": {"DomainUrl":"https://#Environment_test1#/basin","scenarioUrl": "https://#Environment_test1#/basin/api/ScenarioVisualization/","version":"2020.2", "featureNameDashBoard":"master_Baj", "featureNameViewer":"mapvhi" },"rendererServerProtocol":"wss","useGPU":"#Environment_test2#","useGOTF":"#Environment_test3#"}}”,
My script is below:
$Env:Environment_test1 = “testvalue1”
$Env:Environment_test2 = “testvalue2”
$Env:Environment_test3 = “testvalue3”
$file = gci “C:\Users\raman\Config” -Recurse -Depth 1 -filter “*.json” | ? {$.FullName -like “*appsettings.integ.json” } | % { $.FullName }
foreach($i in $file)
{
$tokenRegex = ‘#([A-Z])\w+#’
$tokenrep = '(?<=[#])[a-zA-Z0-9-](?=[#])’
$vars = Get-ChildItem -path env:
$contents = Get-Content -Path $i
$newContents = “”;
$array_list = @()
$Count = [regex]::matches($contents,$tokenRegex)| sort| get-unique
$contents | % {
$line = $
$Count2 = @([regex]::matches($line,$tokenRegex)| sort| get-unique).length
$num = 0
$Count2 = $Count2 -1
if ($Count2 -ge 1)
{
while($num -le $Count2)
{
$token_name = @([regex]::matches($line,$tokenrep)| sort| get-unique)
$array_list = $token_name[$num -1]
$Count_name = @([regex]::matches($line,$tokenRegex)| sort| get-unique)
$regx_val = $Count_name[$num -1]
$setting = Get-ChildItem -path env:* | ? { $.Name -eq $array_list }
if ($setting) {
if ($regx_val -match $array_list )
{
Write-Host “r
n************ token found ************** r
n”
Write-Host “Replacing key $regx_val with value from environment–>” $setting.Value
$setting = Get-ChildItem -path env:* | ? { $.Name -eq $array_list }
$line = $line -replace $regx_val, $setting.Value
}
}
elseIf ([string]::IsNullOrEmpty($array_list))
{
#Write-Host “r
n************ No Value************** r
n”
}
else{
Write-Host “r
n************ token Not found ************** r
n”
Write-Host “r
n token Value = $array_list r
n”
}
$num = $num + 1
}
}
$newContents += $line + [Environment]::NewLine
}
$newContents = $newContents | sort| get-unique
#echo $newContents
Set-Content $i -Value $newContents -Force
}