This post is about removing user profiles from the server running Remote Desktop Services. You could set this up as a scheduled task to periodically remove unwanted or old user profiles.
The cmdlets you will be working with are:
- Get-ChildItem
- Get-CimInstance
- Remove-CimInstance
The logic is simple. The script will extract a list of user profiles under C:\Users directory and put the result in the $FolderList variable excluding those from the $Exclude list. It then grabs those user profile objects using Get-CimInstance cmdlet into the $ProfileList variable. This by default avoids getting the special user profiles such as NetworkService, LocalService and SystemProfile for deletion. Finally, those user profiles are deleted.
So, here is the script!
Function Remove-UserProfile{
Param(
[Parameter()]
[Int]$Day,
[String]$FolderPath,
[String[]]$Exclude
)
Begin{
If($Day -gt 0){
Write-Warning "The Day value should be in negative."
Return
}
$FolderList = Get-ChildItem -Path $FolderPath -Exclude $Exclude -Directory |
Where{[DateTime]$_.LastWriteTime -lt (Get-Date).AddDays($Day)} |
Select-Object -ExpandProperty Name
$ProfileList = Get-CimInstance -ClassName Win32_UserProfile |
Where{$_.LocalPath.split('\')[-1] -in $FolderList}
}
Process{
If($ProfileList){
(Get-Date).ToString() | Add-Content -Path "$FolderPath\DeletionLog.txt"
$ProfileList.LocalPath | Add-Content -Path "$FolderPath\DeletionLog.txt"
Foreach ($User in $ProfileList){
Remove-CimInstance -InputObject $User -ErrorVariable errLog
If ($errLog){
$errLog | Add-Content -Path "$FolderPath\DeletionLog.txt"
}
}
}
}
}
$Config = Import-PowerShellDataFile -Path "$PSScriptRoot\UserProfile-Config.psd1"
Remove-UserProfile -Day $Config.Day -FolderPath $Config.FolderPath -Exclude $Config.Exclude
And this is the config file to go with it.
@{
Day = -30
FolderPath = 'C:\Users'
Exclude = @('Administratror','Public','MSSQL$MICROSOFT##WID','svcAppAccount')
}
This is it for the post!