Deleting domain specific profiles

I had a question regarding these posts:

http://msmvps.com/blogs/richardsiddaway/archive/2012/06.aspx

http://msmvps.com/blogs/richardsiddaway/archive/2013/12/10/1810778.aspx

The question came from someone needing to clean up a set of domain specific profiles.

You can adapt the code in the articles to identify the domain specific profiles like this:

$domain = “mydomain”
Get-CimInstance -ClassName Win32_UserProfile -Filter “Special = ‘$false'” |
select LocalPath, SID, LastUseTime,
@{N=”User”; E={Get-CimInstance -Class Win32_UserAccount -Filter “SID = ‘$($_.SID)'” | select -ExpandProperty Caption}} |
where User -Like “$domain\*”

Once you’ve identified them and ensured that your filters are giving you the correct results you can run this:

$domain = “mydomain”
Get-CimInstance -ClassName Win32_UserProfile -Filter “Special = ‘$false'” |
select LocalPath, SID, LastUseTime,
@{N=”User”; E={Get-CimInstance -Class Win32_UserAccount -Filter “SID = ‘$($_.SID)'” | select -ExpandProperty Caption}} |
where User -Like “$domain\*” |
foreach {
Get-CimInstance -ClassName Win32_UserProfile -Filter “SID = ‘$($_.SID)'” |
Remove-CimInstance -WhatIf

}

NOTICE I’ve left –whatif on the Remove-CimInstance.  It gives you an additional check before you finally commit to deleting the profiles

Alternatively, and better still, put the first set of code into an advanced function and then you can do this:

function get-domainprofile{
[CmdletBinding()]
param (
[string]$domain = “mydomain”
)
Get-CimInstance -ClassName Win32_UserProfile -Filter “Special = ‘$false'” |
select LocalPath, SID, LastUseTime,
@{N=”User”; E={Get-CimInstance -Class Win32_UserAccount -Filter “SID = ‘$($_.SID)'” | select -ExpandProperty Caption}} |
where User -Like “$domain\*”
}

get-domainprofile | foreach {
  Remove-CimInstance -Query “Select * FROM Win32_UserProfile WHERE SID = ‘$($_.SID)'” -WhatIf
}

Again I’ve left –whatif in place. Remove it when you’re happy with the tests

Advertisements
This entry was posted in PowerShell and WMI. Bookmark the permalink.

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