MyITGuy
5/11/2019 - 1:05 PM

Delete User Profiles

Get-CimInstance -ClassName Win32_UserProfile -Filter 'Special != True' | Where-Object LastUseTime -lt (Get-Date).AddDays(-30) | Remove-CimInstance
function Invoke-ProfileBackupAndDelete {
    [CmdletBinding(SupportsShouldProcess=$true)]
    param()

    try {
        #region User Profile
        $BackupDate = Get-Date -format "yyyyMMddhhmmss"

        $UserProfiles = Get-CimInstance -ClassName Win32_UserProfile -Filter "Special != 'True'"
        Write-Host ""
        Write-Host "Please choose:"
        Write-Host ""
        $menu = @{}
        $i = 0
        foreach ($UserProfileItem In $UserProfiles) {
            Write-Host "`t$($i) - $($UserProfileItem.LocalPath)"
            $menu.Add($i, $UserProfileItem)
            $i++
        }
        Write-Host ""
        [int]$Option = Read-Host "Type the number corresponding to the profile to backup and delete"
        $UserProfile = $menu.Item($Option)

        if (!$UserProfile) {
            Write-Warning "User profile not found."
            return
        }
        $UserProfileSID = $UserProfile.SID

        Write-Host @"

You chose:

`t$($UserProfile.SID) - $($UserProfile.LocalPath)

"@

        if ($UserProfile.Loaded -eq $true) {
            Write-Warning "User profile is currently loaded and cannot be modified."
            return
        }

        [string]$DeleteUserProfileQuestion = Read-Host -Prompt "Are you sure you want to delete this user profile? (Y/N, default: Y)"
        if ([System.String]::IsNullOrEmpty($DeleteUserProfileQuestion) -eq $true) { $DeleteUserProfileQuestion = 'Y' }
        [bool]$DeleteUserProfile = $DeleteUserProfileQuestion.ToUpper() -eq 'Y'
        Write-Verbose "DeleteUserProfile: $($DeleteUserProfile)"
        if ($DeleteUserProfile -eq $false) { return }

        if ((Test-Path -Path $UserProfile.LocalPath) -eq $true) {
            [string]$BackupUserProfilePathQuestion = Read-Host -Prompt "Backup the user profile path (otherwise, it will be deleted when the user profile is deleted)? (Y/N, default: Y)"
            if ([System.String]::IsNullOrEmpty($BackupUserProfilePathQuestion) -eq $true) { $BackupUserProfilePathQuestion = 'Y' }
            [bool]$BackupUserProfilePath = $BackupUserProfilePathQuestion.ToUpper() -eq 'Y'
            Write-Verbose "BackupUserProfilePath: $($BackupUserProfilePath)"
        }

        $LocalUserCimObject = Get-LocalUser -SID $UserProfile.SID -ErrorAction SilentlyContinue | Where-Object PrincipalSource -eq 'Local'
        [bool]$DeleteLocalUser = $false
        if ($LocalUserCimObject -is [Microsoft.PowerShell.Commands.LocalUser]) {
            [string]$DeleteLocalUserQuestion = Read-Host "This is a local user. Would you like to delete the local user account? (Y/N, default: N)"
            if ([System.String]::IsNullOrEmpty($DeleteLocalUserQuestion) -eq $true) { $DeleteLocalUserQuestion = 'N' }
            $DeleteLocalUser = $DeleteLocalUserQuestion.ToUpper() -eq 'Y'
        }
        Write-Verbose "DeleteLocalUser: $($DeleteLocalUser)"
        
        if ($BackupUserProfilePath -eq $true) {
            # Rename User Profile Folder
            $UserProfileFolderBackedUp = $false
            $BackupFolderName = "$($UserProfile.LocalPath).$($BackupDate).bak"
            Rename-Item -Path $UserProfile.LocalPath -NewName $BackupFolderName
            $UserProfileFolderBackedUp = Test-Path -Path $BackupFolderName -PathType Container
            if ($UserProfileFolderBackedUp -eq $true) {
                Write-Host "User profile folder backed-up from $($UserProfile.LocalPath) to $($BackupFolderName)"
            } else {
                Write-Host "User profile folder not backed-up." -ForegroundColor Red
                if ( $DeleteUserProfile -ne $false) { $DeleteUserProfile = $false }
                Write-Verbose "DeleteUserProfile (changed): $($DeleteUserProfile)"
                if ( $DeleteLocalUser -ne $false) { $DeleteLocalUser = $false }
                Write-Verbose "DeleteLocalUser (changed): $($DeleteLocalUser)"
            }
        }

        # Remove profile
        if ($DeleteUserProfile -eq $true) {
            try {
                $UserProfile | Remove-CimInstance
                Write-Host "User profile deleted."
            }
            catch {
                Write-Host "User profile not deleted. $($_.Exception.Message.Trim())" -ForegroundColor Red
            }
        }
        #endregion User Profile

        #region Local User
        if ($DeleteLocalUser -eq $true) {
            try {
                Get-LocalUser -SID $UserProfileSID | Remove-LocalUser
                Write-Host "User account deleted."
            } catch {
                Write-Host "User account not deleted. $($_.Exception.Message.Trim())" -ForegroundColor Red
            }
        }
        #endregion Local User
    }
    catch {
        Throw $_
    }
}