Search code examples
powershellpowershell-4.0

Simple script to delete old user profiles


I am writing a simple script that will be used to delete user profiles older than 90 days. I can capture the profiles that I want but, when it comes to the "bread and butter" I am stumped.

My code:

$localuserprofiles = Get-WmiObject -Class Win32_UserProfile | Select-Object localPath,@{Expression={$_.ConvertToDateTime($_.LastUseTime)};Label="LastUseTime"}| Where{$_.LocalPath -notlike "*$env:SystemRoot*"} #Captures local user profiles and their last used date
$unusedday = 90 # Sets the unused prifile time threshold
$excludeduserpath = $excludeduser.LocalPath # Excludes the DeltaPC user account
$profilestodelete = $LocalUserProfiles | where-object{$_.lastusetime -le (Get-Date).AddDays(-$unusedday) -and $_.Localpath -notlike "*$excludeduserpath*"} #Captures list of user accounts to be deleted

#Deletes unused Profiles

Foreach($deletedprofile in $profilestodelete)
    {
        $deletedprofile.Delete()
    }

The code returns this error:

Method invocation failed because [Selected.System.Management.ManagementObject] does not contain a method named 'Delete'. 
At line:3 char:13 
+ $deletedprofile.Delete()} 
+ ~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo : InvalidOperation: (Delete:String) [], RuntimeException 
    + FullyQualifiedErrorId : MethodNotFound

Solution

  • Because you're getting WMI Objects, you can use the Remove-WMIObject cmdlet.

    So, simply modifying the deletion loop like this should remove the desired profiles correctly and completely:

    Foreach($deletedprofile in $profilestodelete)
        {
            Remove-WMIObject $deletedprofile
        }