User profiles and last use
Win32_UserProfile describes one profile per account that has signed in. It holds only the SID: the script translates it to a name with [System.Security.Principal.SecurityIdentifier].
function ConvertTo-AccountName {
[CmdletBinding()]
param (
[string]
$Sid
)
try {
$securityIdentifier = [System.Security.Principal.SecurityIdentifier]::new($Sid)
$securityIdentifier.Translate([System.Security.Principal.NTAccount]).Value
} catch {
$Sid
}
}
Get-CimInstance -ClassName Win32_UserProfile -Filter 'Special = FALSE' |
Select-Object -Property @(
@{ Name = 'Account'; Expression = { ConvertTo-AccountName -Sid $_.SID } }
'LocalPath'
'Loaded'
'LastUseTime'
) |
Sort-Object -Property LastUseTime
Special = FALSE drops the system profiles (LocalSystem, LocalService, NetworkService). If the SID cannot be resolved (deleted account, unreachable domain), the function returns the SID itself. LastUseTime is a [datetime]. The translation runs on the machine that runs the script: for a remote server, the local accounts of that server stay shown as SIDs.
Variant: profiles unused for 180 days
Warning: removing a Win32_UserProfile instance deletes the profile folder and its registry hive. Keep -WhatIf until the list is validated, and back up the data if needed.
$limitDate = (Get-Date).AddDays(-180)
$profileFilter = 'Special = FALSE AND Loaded = FALSE'
$oldProfile = Get-CimInstance -ClassName Win32_UserProfile -Filter $profileFilter |
Where-Object -FilterScript { $_.LastUseTime -lt $limitDate }
# Simulation: -WhatIf only shows what would be deleted
$oldProfile |
Remove-CimInstance -WhatIf