1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| function Test-ConfigDrift { param( [Parameter(Mandatory)] [string]$BaselinePath,
[Parameter(Mandatory)] [string]$CurrentPath,
[string]$KeyProperty = "Name" )
$baseline = Get-Content $BaselinePath -Raw | ConvertFrom-Json $current = Get-Content $CurrentPath -Raw | ConvertFrom-Json
$drifts = @()
foreach ($baseItem in $baseline) { $key = $baseItem.$KeyProperty $currentItem = $current | Where-Object { $_.$KeyProperty -eq $key }
if (-not $currentItem) { $drifts += [PSCustomObject]@{ Key = $key Type = "MISSING" Property = "ALL" Expected = "存在" Actual = "不存在" } continue }
foreach ($prop in $baseItem.PSObject.Properties.Name) { if ($baseItem.$prop -ne $currentItem.$prop) { $drifts += [PSCustomObject]@{ Key = $key Type = "CHANGED" Property = $prop Expected = $baseItem.$prop Actual = $currentItem.$prop } } } }
foreach ($curItem in $current) { $key = $curItem.$KeyProperty $baseItem = $baseline | Where-Object { $_.$KeyProperty -eq $key } if (-not $baseItem) { $drifts += [PSCustomObject]@{ Key = $key Type = "ADDED" Property = "ALL" Expected = "不存在" Actual = "存在" } } }
if ($drifts) { Write-Host "检测到 $($drifts.Count) 处配置漂移:" -ForegroundColor Red $drifts | Format-Table -AutoSize } else { Write-Host "配置与基准一致" -ForegroundColor Green }
return $drifts }
$baselineJson = @' [ {"Name":"SRV01","IP":"10.0.1.1","Role":"Web","Status":"Active"}, {"Name":"SRV02","IP":"10.0.1.2","Role":"DB","Status":"Active"}, {"Name":"SRV03","IP":"10.0.1.3","Role":"App","Status":"Active"} ] '@
$currentJson = @' [ {"Name":"SRV01","IP":"10.0.1.1","Role":"Web","Status":"Maintenance"}, {"Name":"SRV02","IP":"10.0.2.2","Role":"DB","Status":"Active"}, {"Name":"SRV04","IP":"10.0.1.4","Role":"Web","Status":"Active"} ] '@
$baselineJson | Set-Content "C:\Config\baseline.json" -Encoding UTF8 $currentJson | Set-Content "C:\Config\current.json" -Encoding UTF8
Test-ConfigDrift -BaselinePath "C:\Config\baseline.json" -CurrentPath "C:\Config\current.json" -KeyProperty "Name"
|