用于比较两个文件之间的参数并将值覆盖到主文件中的 powershell 脚本

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

我是 power 的新手 shell,如果您能帮我解决这个问题,我将不胜感激。 如果子文件存在,我需要比较两个参数($$Daily_Test、$$Monthly_Test)并将子值替换到父文件中。

看看下面的命令是否对您有帮助。根据您的示例内容,将首先处理子文件并创建一个字典,然后更新所有匹配的键 (全部,不只是具体 $$Daily_Test 和 $$Monthly_Test) 在父文件中,如果它们存在于子文件中;键是 = 符号之前的部分。

我建议在测试之前创建父文件的副本。这已经在 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