Delprof Alternative

So I wrote this ugly code quite some time ago. Since I have seen a few new posts in the script gallery with versions I figured I should at least post a version of what I had done a few years ago and re-used recently. Situations like shared computers and RDS can have a computer looking ragged with local profiles created on login and then not touched again. This causes capacity issues but can also cause performance issues. There used to be a utility called delprof which was great but even if it were around why not script it right?

Function clean-localprofiles {
    [CmdletBinding()]
    Param (
        [Parameter(Position = 0)]
        [ValidateNotNullorEmpty()]
        [int]$Days = 30,
        [string]$rptFile = "somefile name here"
    )
    BEGIN 
    {
        "---- Internal RDS Profile Monitor Start {0}" -f (get-date -f "MM/dd/yy hh:mm") | out-file $rptFile -Append
        Write-Warning "Filtering for user profiles older than $Days days"
        $profs = Get-CimInstance win32_userprofile -ComputerName computer1, computer2  |
        Where { $_.LastUseTime -lt $(Get-Date).Date.AddDays(- $days) -AND $_.SID.Length -gt 8 -AND $_.Loaded -eq $False }
    }
    PROCESS
    {
        ForEach ($obj in $profs) {
            $uname = $obj.LocalPath.Split("\") | select -Last 1
            "Removing profile for {0} from {1} which was last used {2}" -f $uname, $obj.pscomputername, $obj.LastUseTime |
            out-file $rptFile -Append
            Try {
                Remove-CimInstance -InputObject $obj -ComputerName $obj.pscomputername
            }
            Catch {
                "Unable to remove profile" | out-file $rptFile -Append
            }       
        }
        # Complete
    }
    END
    {
        "---- Internal RDS Profile Monitor Complete {0}" -f (get-date -f "MM/dd/yy hh:mm") |
            out-file $rptFile -Append
    }    
}
Clean-localprofiles

That’s about it. I updated the process from WMI to CIM (where possible) and tweaked based on changes to Powershell but relatively unchanged. Yeah checked my OneDrive, first script was dated in 2012…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s