I would like to delete any user profiles older than 30 days prior to backing up a client system. I am getting an access denied when trying to remove the c:\users\jsmith\AppData\Local\Application Data’ directory. Also is there any way to delete all the registry info associated with that user?
I have to use powershell v2
Here is what i have so far … thanks
[cmdletbinding(SupportsShouldProcess)]
Param(
[Parameter(Position=0)]
[ValidateNotNullorEmpty()]
[int]$Days= 30
)
Write-Warning "Filtering for user profiles older than $Days days"
$profile = gwmi win32_userprofile | ? {$_.localpath -like "*c:\users\*" -and $_.localpath -notlike "C:\Users\Administrator"} |
select localpath,@{ Name = "lastUseTime" ; Expression = { $_.Converttodatetime( $_.LastuseTime ) } } |
Where {$_.LastUseTime -lt $(Get-Date).AddDays(-$days)}
if ($profile -eq $null){Write-Host "No user profiles older than $Days days where found "
}
else {
remove-item $profile.localpath -Recurse -Force
}
There is a lot of fuss about if the .Delete method exists or not, it is not in the MSDN, however I just did it on a test 2008R2 machine and it worked as expected.
Deleting user profiles is a tricky business. I believe PowerShell is not the right tool for the job. We’re using Helge Klein’s Delprof2 tool at work which does exactly this job very well without issues.
Just so you understand the problem with your script. You are generating a PSObject from Get-WMIObject, so the object doesn’t have a .Delete() method (even if it did, it would just manipulate the PSObject, not the profiles). As soon as you use Select-Object, you are generating a PSObject. That is why the example Raymond provided worked using an implicit foreach (available in v3 and above). If you are using Powershell V2, you would have to explicitly use a foreach:
You should also look at some of the Win32_UserProfile properties such as Special (indicates a SYSTEM, NETWORK, ADMINISTRATOR profile) and Loaded (indicates a profile is loaded in registry) to do your filtering. You are specifically looking for “Administrator” and not other system profiles in your filter plus it should be done in WMI filtering, not after. See what is returned with this:
gwmi Win32_UserProfile -Filter "Loaded=False And Special=False"
Lastly, I’ve had issues deleting profiles in Terminal Server environments because of long path\files which AppData contains temporary internet files that I usually find the culprit. Attached is a script that I wrote for our Citrix\TS folks and it seemed to work without issue and provided logging indicating why a profile was skipped or deleted. The script is writted to support -WhatIf, so make sure you test, then test, test again in a non-production environment: