Public/Invoke-ProfileGuardian.ps1
|
<#
.SYNOPSIS Runs the governed profile-lifecycle workflow for a local Windows drive. .DESCRIPTION Checks disk pressure, discovers eligible stale profiles and reports the planned action. Profiles are removed only when Execute is supplied and ShouldProcess approves the action. Cleanup stops at the target utilisation or safety cap. .PARAMETER TriggerPercent The used-space percentage at which profile assessment begins. .PARAMETER TargetPercent The used-space percentage at which an executing cleanup stops. .PARAMETER MinimumAgeDays The minimum number of inactive days required for profile eligibility. .PARAMETER MaxProfiles The maximum number of profiles that may be removed in one run. .PARAMETER Drive The local drive whose utilisation gates cleanup. When omitted, the drive is derived from ProfileRoot. .PARAMETER ProfileRoot The directory whose immediate child directories contain local user profiles. The default is the Windows ProfilesDirectory setting. .PARAMETER ProtectedProfileName Additional profile directory names that must never be removed. .PARAMETER LogDirectory The directory receiving text and JSON Lines run records. .PARAMETER Execute Enables approved removal. Without this switch, the command is report-only. .EXAMPLE Invoke-ProfileGuardian -TriggerPercent 70 -TargetPercent 65 -MinimumAgeDays 10 .EXAMPLE Invoke-ProfileGuardian -TriggerPercent 70 -TargetPercent 65 -Execute -WhatIf .OUTPUTS ProfileGuardian.RunSummary #> function Invoke-ProfileGuardian { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param( [ValidateRange(1, 99)] [int]$TriggerPercent = 70, [ValidateRange(1, 99)] [int]$TargetPercent = 65, [ValidateRange(1, 3650)] [int]$MinimumAgeDays = 10, [ValidateRange(1, 100)] [int]$MaxProfiles = 5, [string]$Drive, [string]$ProfileRoot, [string[]]$ProtectedProfileName = @(), [string]$LogDirectory, [switch]$Execute ) if ($TargetPercent -ge $TriggerPercent) { throw 'TargetPercent must be lower than TriggerPercent.' } Assert-PGWindows $resolvedProfileRoot = Resolve-PGProfileRoot -Drive $Drive -ProfileRoot $ProfileRoot $profileDrive = Get-PGDriveFromProfileRoot -ProfileRoot $resolvedProfileRoot $resolvedDrive = if ([string]::IsNullOrWhiteSpace($Drive)) { $profileDrive } else { Resolve-PGDrive -Drive $Drive } if ($resolvedDrive -ne $profileDrive) { throw "Drive '$resolvedDrive' does not contain ProfileRoot '$resolvedProfileRoot'." } $resolvedLogDirectory = Resolve-PGLogDirectory -LogDirectory $LogDirectory $runId = [guid]::NewGuid().ToString() $runLock = $null $startedRecordWritten = $false try { $runLock = Enter-PGRunLock -Drive $resolvedDrive $before = Get-PGDiskPressure -Drive $resolvedDrive Write-PGRunRecord -LogDirectory $resolvedLogDirectory -Level INFO -Message 'Profile lifecycle check started.' -Data @{ runId = $runId drive = $resolvedDrive profileRoot = $resolvedProfileRoot usedPercent = $before.UsedPercent triggerPercent = $TriggerPercent targetPercent = $TargetPercent minimumAgeDays = $MinimumAgeDays maxProfiles = $MaxProfiles execute = [bool]$Execute whatIf = [bool]$WhatIfPreference } $startedRecordWritten = $true $candidates = @() $removedCount = 0 $status = 'BelowTrigger' $after = $before if ($before.UsedPercent -ge $TriggerPercent) { $candidates = @(Get-PGStaleProfile ` -MinimumAgeDays $MinimumAgeDays ` -Drive $resolvedDrive ` -ProfileRoot $resolvedProfileRoot ` -ProtectedProfileName $ProtectedProfileName) if ($candidates.Count -eq 0) { $status = 'NoEligibleProfiles' } elseif (-not $Execute) { $status = 'ReportOnly' } elseif ($WhatIfPreference) { $status = 'WhatIf' } else { $status = 'NoProfilesRemoved' } foreach ($candidate in @($candidates | Select-Object -First $MaxProfiles)) { if (-not $Execute) { break } $current = Get-PGDiskPressure -Drive $resolvedDrive if ($current.UsedPercent -le $TargetPercent) { $status = 'TargetReached' break } if ($PSCmdlet.ShouldProcess("$($candidate.LocalPath) [$($candidate.Sid)]", 'Remove stale Windows profile')) { $result = Remove-PGStaleProfile ` -Sid $candidate.Sid ` -MinimumAgeDays $MinimumAgeDays ` -Drive $resolvedDrive ` -ProfileRoot $resolvedProfileRoot ` -ProtectedProfileName $ProtectedProfileName ` -Confirm:$false if ($result.Removed -and $result.Verified) { $removedCount++ $status = 'ProfilesRemoved' Write-PGRunRecord -LogDirectory $resolvedLogDirectory -Level INFO -Message 'Profile removed.' -Data @{ runId = $runId sid = $result.Sid localPath = $result.LocalPath lastActivity = $result.LastActivity ageSource = $result.AgeSource verified = $result.Verified } } } elseif ($WhatIfPreference) { $status = 'WhatIf' } else { $status = 'Declined' break } } $after = Get-PGDiskPressure -Drive $resolvedDrive if ($Execute -and -not $WhatIfPreference -and $after.UsedPercent -le $TargetPercent) { $status = 'TargetReached' } elseif ( $Execute -and -not $WhatIfPreference -and $removedCount -ge $MaxProfiles -and $candidates.Count -gt $removedCount ) { $status = 'SafetyCapReached' } } Write-PGRunRecord -LogDirectory $resolvedLogDirectory -Level INFO -Message 'Profile lifecycle check completed.' -Data @{ runId = $runId status = $status initialUsedPercent = $before.UsedPercent finalUsedPercent = $after.UsedPercent eligibleProfiles = $candidates.Count removedProfiles = $removedCount } $summary = [pscustomobject]@{ RunId = $runId Status = $status Drive = $resolvedDrive ProfileRoot = $resolvedProfileRoot InitialUsedPercent = $before.UsedPercent FinalUsedPercent = $after.UsedPercent EligibleProfiles = $candidates.Count RemovedProfiles = $removedCount LogDirectory = $resolvedLogDirectory } $summary.PSObject.TypeNames.Insert(0, 'ProfileGuardian.RunSummary') return $summary } catch { if ($startedRecordWritten) { try { Write-PGRunRecord -LogDirectory $resolvedLogDirectory -Level ERROR -Message 'Profile lifecycle check failed.' -Data @{ runId = $runId error = $_.Exception.Message } } catch { Write-Verbose 'The audit failure record could not be written; preserving the operational error.' } } throw } finally { Exit-PGRunLock -LockHandle $runLock } } |