Delete any user profiles that haven't been logged into in the last 6 months using Cim and Powershell Delete any user profiles that haven't been logged into in the last 6 months using Cim and Powershell powershell powershell

Delete any user profiles that haven't been logged into in the last 6 months using Cim and Powershell


How to delete user profiles older than a specified number of days in Windows

This PowerShell script sample shows how to delete user profiles older than a specified number of days.

Example 1:  C:\Script\RemoveLocalUserProfile.ps1 -ListUnusedDay 1Example 2: C:\Script\RemoveLocalUserProfile.ps1 -DeleteUnusedDay 1 -ExcludedUsers “marry” # Begin ScriptIf ($ProfileInfo -eq $null) {     Write-Warning -Message "The item not found." } Else {     Foreach ($RemoveProfile in $ProfileInfo)     {         #Prompt message         $Caption = "Remove Profile"         $Message = "Are you sure you want to remove profile '$($RemoveProfile.LocalPath)'?"         $Choices = [System.Management.Automation.Host.ChoiceDescription[]]`         @("&Yes", "&No")         [Int]$DefaultChoice = 1         $ChoiceRTN = $Host.UI.PromptForChoice($Caption, $Message, $Choices, $DefaultChoice)         Switch ($ChoiceRTN)         {             0            {                 Try {$RemoveProfile.Delete(); Write-Host "Delete profile '$($RemoveProfile.LocalPath)' successfully."}                 Catch {Write-Host "Delete profile failed." -ForegroundColor Red}             }             1 {break}         }     }     $ProfileInfo|Select-Object @{Expression = {$_.__SERVER}; Label = "ComputerName"}, `     @{Expression = {$_.ConvertToDateTime($_.LastUseTime)}; Label = "LastUseTime"},`     @{Name = "Action"; Expression = {If (Test-Path -Path $_.LocalPath)             {"Not Deleted"}             Else             {"Deleted"}         }    } }# End Script

Similar approaches can be see here:

https://community.spiceworks.com/how_to/124316-delete-user-profiles-with-powershell

https://www.business.com/articles/powershell-manage-user-profiles


Take care when deleting profiles, you don't want to hit machine special accounts. The Win32_UserProfile class has a LastUseTime property you can rely on.

$session = New-CimSession -ComputerName $cn$gcimParams = @{    'CimSession' = $session    'ClassName'  = 'Win32_UserProfile'    'Filter'     = 'RefCount<1 and Special="false" and Loaded="false"'}$profileList = (Get-CimInstance @gcimParams).Where{$PSItem.LastUseTime -lt (Get-Date).AddMonths(-6)}foreach ($user in $profileList){    $user | Remove-CimInstance -CimSession $session}