All but User1 and User2
# Get the list of currently logged-on users
$loggedOnUsers = quser 2>$null | Select-Object -Skip 1 | ForEach-Object {
$_.Trim().Split(' ')[0]
}
$profilesToRemove = Get-CimInstance -ClassName Win32_UserProfile | Where-Object {
$username = $_.LocalPath.Split('\')[-1]
($_.LocalPath -like "*") -and
($_.LocalPath -notlike "*user1*") -and
($_.LocalPath -notlike "*user2*") -and
($_.LocalPath -notlike "C:\WINDOWS\ServiceProfiles\NetworkService") -and
($_.LocalPath -notlike "C:\WINDOWS\ServiceProfiles\LocalService") -and
($_.LocalPath -notlike "C:\WINDOWS\system32\config\systemprofile") -and
($loggedOnUsers -notcontains $username)
}
# Display profiles to be removed
$profilesToRemove | ForEach-Object {
Write-Output "Profile to remove: $($_.LocalPath)"
}
# Remove the profiles
$profilesToRemove | ForEach-Object {
$_ | Remove-CimInstance -Confirm:$false
Write-Output "Removed profile: $($_.LocalPath)"
}
Specific username:
Get-CimInstance -ClassName win32_UserProfile | Where-Object {$_.LocalPath -like "*username*"} | Remove-CimInstanceOlder than 30 days:
Get-CimInstance -ClassName win32_userprofile | Where-Object {(!$_.Special) -and ($_.LastUseTime -lt (Get-Date).AddDays(-30)) } | Remove-CimInstanceGet Profiles list:
Get-CimInstance -ClassName Win32_UserProfile -Property * -Filter "Special ='False'" |
Select LocalPath,
LastUseTime,
@{Name='Folder Date';Expression={Get-Item -Path $_.LocalPath | Select -ExpandProperty LastAccessTime}},
@{Name='NTUser Date';Expression={Get-Item -Path ($_.LocalPath + "\NTUSER.DAT") -Force | Select -ExpandProperty LastAccessTime}}