if ($DoRemoval -and $explicitRules.Count -gt 0) { if ($ExcludeRootFromRemoval -and $isRoot) { continue } $changed = $false # Collect unique, non-whitelisted SIDs present in explicit rules $sidStrings = @() foreach ($r in $explicitRules) { $sidStr = $null try { $sidStr = $r.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value } catch { $sidStr = $r.IdentityReference.Value } if ($sidStr -and -not $WhitelistSidSet.Contains($sidStr)) { $sidStrings += $sidStr } } $sidStrings = $sidStrings | Select-Object -Unique # Purge all explicit ACEs for each target SID in one shot foreach ($sidStr in $sidStrings) { try { $sid = New-Object System.Security.Principal.SecurityIdentifier($sidStr) $acl.PurgeAccessRules($sid) $changed = $true } catch { # Last-resort fallback if the SID ctor fails for any reason foreach ($r in $explicitRules) { try { $null = $acl.RemoveAccessRuleSpecific($r); $changed = $true } catch {} } } } if ($changed) { Set-Acl -LiteralPath $item.FullName -AclObject $acl Add-Content -LiteralPath $FixLog -Value ('Purged explicit ACEs from: ' + $item.FullName) } }