User Profile Cleanup

Download Cleanup-UserProfiles.ps1

Big environments get messy, lots of users, lots of admins, lots of logging in here and there.

Profiles accumulate, C drive starts to get full, oh the humanity! Fear not humble Admin, on our adventures today we discover how to remove old user profiles with naught but the flick of a WMI method.

The meat and bonse of this function is getting user profiles and deleting them:

$userprofiles = Get-WmiObject -Class Win32_UserProfile
$userprofiles[$whichOne].delete()

But before we can pull the trigger and send these profiles to the depths, there will be some evaluation of dates, some checking that they aren’t important, and some validating using ShouldProcess.

[CmdletBinding(
     SupportsShouldProcess=$true,
    ConfirmImpact="High"
  )]param ($computerName= '.',$AgeLimit='60', $Exclude)

By declaring supportsShouldProcess=$true it means that we can make use of the COnfirm/Force/Whatif because deleting user profiles is surely an activity to be feared. What if you delete a service account profile? Your best friend Greg? Such activities are the folley of adventurous Admins.

By wrapping our dangerous bits in $Pscmdlet.shouldProcess("The thing I am about to do") we can give the Admin a chance to save their skin, and their friendships.

 if ($pscmdlet.ShouldProcess($activity)) {
        Write-Verbose "Attempting to $activity"
        $profile.Delete()       
    }

Go forth wayward Admin, delete those profiles, watch as you recover untold disk space and make the data gods smile.

Download Cleanup-UserProfiles.ps1