AzureDataFactoryV2/RegExReplace/Scripts/Replace-Values.ps1

# halt on first error
$ErrorActionPreference = "Stop"
# print Information stream
$InformationPreference = "Continue"

# if executed from PowerShell ISE
if ($psise) { 
  $rootPath = Split-Path -Parent $psise.CurrentFile.FullPath | Split-Path -Parent
}
else {
  $rootPath = (Get-Item $PSScriptRoot).Parent.FullName
}

$armFile = Get-ChildItem -Path $rootPath -Recurse -Filter "ARMTemplateForFactory.json" | SELECT -First 1
$armFileWithReplacedValues = $armFile.FullName.Replace($armFile.Name, "ARMTemplate_wReplacedValues.json")

$json = Get-Content $armFile.FullName

[xml]$configFile = Get-Content -Path "$rootPath\Scripts\Replace-Values.config.xml"

foreach($valueToReplace in $configFile.valuesToReplace.valueToReplace)
{
  if($valueToReplace.isActive -eq $true)
  { 
    $regEx = $valueToReplace.regExSearch
    $replaceValue = '$1' + $valueToReplace.replaceWith + '$3'
  
    $matches = [regex]::Matches($json, $regEx)
    Write-Information "Found $($matches.Count) matches for $regex !"
    if($matches.Count -eq 0)
    {
      Write-Warning "The regular expression '$regEx' was not found! Make sure it is correct and the input text contains a match!"
    }
    
    $matches
  
    $json = [regex]::Replace($json, $regEx, $replaceValue)
  }
  else
  {
    Write-Warning "Inactive config value: The regular expression '$($valueToReplace.regExSearch)' is not marked as active - nothing will be replaced!"
  }
}

Write-Information "Writing JSON with replaced values to $armFileWithReplacedValues"
$json | Out-File $armFileWithReplacedValues