Skip to content

Instantly share code, notes, and snippets.

@automationhaus
Last active January 21, 2017 02:00
Show Gist options
  • Save automationhaus/22a18fc996735909e14d9117d6deccfe to your computer and use it in GitHub Desktop.
Save automationhaus/22a18fc996735909e14d9117d6deccfe to your computer and use it in GitHub Desktop.
Remotely Remove User Profiles from RDS or Citrix Session Host Servers
<#
I broke out the Get-CIMInstance and Get-WMIObject types for a couple of reasons. 1. Because I kept running into issues on 2008 R2
where CIM wasn't working due to the fact they aren't configured for remoting out of the box like 2012 servers are. 2. In order to
train system admins on how to use both versions in case one or the other doesn't work for them. Here, I break down the two based
on the version of the OS but you can elect to use one or the other depening on your environment. In CIM you can specify the protocol
type which could help eliminate the need for the WMI version but the WMI version will be supported on servers with older versions
of PowerShell.
#>
#Specifying the EAP
$ErrorActionPreference = "Stop"
#Create a decimal based OS version since CIMInstance doesn't work below version 6.2
$OSVersion = [decimal]([environment]::OSVersion.Version.Major,[environment]::OSVersion.Version.Minor -join ".")
#The name of the user's profile folder as it exists on the session host
$ProfileNames = @("username.DOMAIN","username1.DOMAIN")
#Array of session host servers
$Servers = @("RDSH01","RDSH02","RDSH03","RDSH04","RDSH05")
""
$Servers |
%{
try
{
foreach($P in $ProfileName)
{
Write-Host "Removing the " -NoNewLine
Write-Host $P -NoNewline -ForegroundColor Yellow
Write-host " profile from " -NoNewline
Write-Host $_ -ForegroundColor Cyan
#Machines 2012 and newer use CIM
$Filter = "localpath='C:\\Users\\$P'"
if($OSVersion -ge 6.2)
{
$X = Get-CimInstance Win32_UserProfile -Computer $_ -filter "$Filter" |
Remove-CimInstance
}
else
{
$X = Get-WmiObject Win32_UserProfile -Computer $_ -filter "$Filter"
$X.Delete()
}
Write-Host "- Successfully removed" -ForegroundColor Green
}
}
catch
{
Write-Host "- $($_.Exception.Message)" -ForegroundColor Red
}
}
""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment