Private/Remove-PGStaleProfile.ps1

<#
.SYNOPSIS
Removes one local Windows profile after revalidating its eligibility.
 
.DESCRIPTION
Re-queries the profile by SID and repeats the loaded, protected and age checks
immediately before removal. The command requires elevation for an approved
removal and supports WhatIf and Confirm.
 
.PARAMETER Sid
The Windows SID of the profile to assess and remove.
 
.PARAMETER MinimumAgeDays
The minimum number of inactive days required for removal.
 
.PARAMETER Drive
The local drive used when Windows does not provide a profile-root setting.
 
.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.
 
.EXAMPLE
Remove-PGStaleProfile -Sid 'S-1-5-21-111-222-333-1001' -WhatIf
 
.OUTPUTS
ProfileGuardian.RemovalResult
#>

function Remove-PGStaleProfile {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param(
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [ValidatePattern('^S-\d(?:-\d+)+$')]
        [string]$Sid,

        [ValidateRange(1, 3650)]
        [int]$MinimumAgeDays = 10,

        [string]$Drive,

        [string]$ProfileRoot,

        [string[]]$ProtectedProfileName = @()
    )

    process {
        Assert-PGWindows
        $resolvedProfileRoot = Resolve-PGProfileRoot -Drive $Drive -ProfileRoot $ProfileRoot
        $userProfile = Get-PGProfileBySid -Sid $Sid
        if ($null -eq $userProfile) {
            throw "Profile '$Sid' was not found."
        }

        $reason = Test-PGProfileBaseEligibility -UserProfile $userProfile -ProfileRoot $resolvedProfileRoot -ProtectedProfileName $ProtectedProfileName
        if ($null -ne $reason) {
            throw "Profile '$Sid' is not eligible for removal: $reason."
        }

        $activity = Get-PGProfileActivity `
            -Sid $Sid `
            -LocalPath ([string]$userProfile.LocalPath) `
            -LastUseTime $userProfile.LastUseTime
        if ($null -eq $activity) {
            throw "Profile '$Sid' has no reliable activity timestamp."
        }
        if ($activity.Timestamp -ge (Get-Date).AddDays(-$MinimumAgeDays)) {
            throw "Profile '$Sid' is not older than $MinimumAgeDays days."
        }

        $removed = $false
        $verified = $false
        if ($PSCmdlet.ShouldProcess("$($userProfile.LocalPath) [$Sid]", 'Remove stale Windows profile')) {
            Assert-PGAdministrator

            $userProfile = Get-PGProfileBySid -Sid $Sid
            if ($null -eq $userProfile) {
                throw "Profile '$Sid' disappeared before removal."
            }

            $reason = Test-PGProfileBaseEligibility -UserProfile $userProfile -ProfileRoot $resolvedProfileRoot -ProtectedProfileName $ProtectedProfileName
            if ($null -ne $reason) {
                throw "Profile '$Sid' is not eligible for removal after confirmation: $reason."
            }

            $activity = Get-PGProfileActivity `
                -Sid $Sid `
                -LocalPath ([string]$userProfile.LocalPath) `
                -LastUseTime $userProfile.LastUseTime
            if ($null -eq $activity) {
                throw "Profile '$Sid' has no reliable activity timestamp after confirmation."
            }
            if ($activity.Timestamp -ge (Get-Date).AddDays(-$MinimumAgeDays)) {
                throw "Profile '$Sid' is no longer older than $MinimumAgeDays days."
            }

            Invoke-PGProfileCimRemoval -UserProfile $userProfile
            $removed = $true
            $verified = Wait-PGProfileAbsent -Sid $Sid
            if (-not $verified) {
                throw "Windows accepted removal for profile '$Sid', but the profile remained visible after the verification timeout."
            }
        }

        $result = [pscustomobject]@{
            Sid          = $Sid
            LocalPath    = [string]$userProfile.LocalPath
            LastActivity = $activity.Timestamp
            AgeSource    = $activity.Source
            Removed      = $removed
            Verified     = $verified
        }
        $result.PSObject.TypeNames.Insert(0, 'ProfileGuardian.RemovalResult')
        return $result
    }
}