Search code examples
powershellpowershell-2.0powershell-3.0powershell-4.0

powershell script to compare parameters between two files and override values into main file


I'm new to power shell and i would greatly appreciate you all if you can help me to fix this. if child file existed, I need to compare two parameters ($$Daily_Test, $$Monthly_Test) and replace child values into parent file.

enter image description here


Solution

  • See if below commands help you. Based on your example content will first process the child file and create a dictionary, and then update the all matching keys (all, not just specifically $$Daily_Test and $$Monthly_Test) in parent file if they are present in the child file; key being the part before = sign.

    I would suggest to create a copy of parent file before testing this. This has been tested on PowerShell 5.1.

    # Read the contents of both files
    $parentContent = @(Get-Content -Path .\parent.txt)
    $childContent = @(Get-Content -Path .\child.txt)
    
    # Create a dictionary to hold values from child file
    $childDict=@{}
    $childContent | ForEach-Object -Process {
    $spl = $_ -split '='
    if ($spl.Count -eq 2 -and -not [string]::IsNullOrWhiteSpace($spl[1])) { $childDict.Add($spl[0], $spl[1]) }
    }
    
    # Update the values from child in parent content
    
    $modifiedParentContent=@()
    
    $parentContent | ForEach-Object -Process {
    $line = $_
    $spl = $line -split '='
    if ($spl[0] -in $childDict.Keys) {
    $modifiedParentContent += "$($spl[0])=$($childDict[$spl[0]])"
    }
    else {
    $modifiedParentContent += $line
    }
    }
    
    # Overwrite the parent file
    Set-Content -Path .\parent.txt -Value $modifiedParentContent