As promised in my previous post,I am back with a Powershell script which helps you in deleting a user’s windows profile either on local computer or on multiple remote computers. This script users Win32_UserProfile class which is available in Windows Vista, Windows 7, and Windows 2008(R2). So it will not work for Windows XP and 2003 hosts.
In this script I am making use of a method called Delete() which is available for each profile queried through Win32_UserProfile WMI class. Using this script you can delete one profile at a time on a single computer or list of remote computers. This script will also display the result of operation you are performing. That means it will tell whether it succeed in deleting the profile or failed. And it will also tell you if the script is unable to find the profile you are trying to delete.
Code: Remove-UserProfile.ps1
[cmdletbinding()] param( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$ComputerName = $env:computername, [parameter(mandatory=$true)] [string]$UserName ) Begin {} Process { foreach($Computer in $ComputerName) { Write-Verbose "Working on $Computer" if(Test-Connection -ComputerName $Computer -Count 1 -ea 0) { $Profiles = Get-WmiObject -Class Win32_UserProfile -Computer $Computer -ea 0 foreach ($profile in $profiles) { $objSID = New-Object System.Security.Principal.SecurityIdentifier($profile.sid) $objuser = $objsid.Translate([System.Security.Principal.NTAccount]) $profilename = $objuser.value.split("\")[1] if($profilename -eq $UserName) { $profilefound = $true try { $profile.delete() Write-Host "$UserName profile deleted successfully on $Computer" } catch { Write-Host "Failed to delete the profile, $UserName on $Computer" } } } if(!$profilefound) { write-Warning "No profiles found on $Computer with Name $UserName" } } else { write-verbose "$Computer Not reachable" } } } end {}
Output:
You can use this script to delete profile from list of remote computers either by providing the list via command line or using a text file. See below two cases to get more insight about how to use the script in such cases.
.\Remove-UserProfile.ps1 -ComputerName PC1, PC2, PC3 -UserName LocalUser2
Get-Content c:\temp\Computers.txt | .\Remove-UserProfile.ps1 -UserName LocalUser2
Hope this helps… Feel free to write in comments section if you have any doubts or looking for some enhancements to the script. Happy to help.
Comments on this entry are closed.
I just get “Some or all identity references could not be translated.”, something I’m missing?
Full error:
PS C:\Users\lab-jimw\Desktop> .\delete2008profile.ps1 -ComputerName 2008tester -UserName lab-jimw
Exception calling “Translate” with “1” argument(s): “Some or all identity references could not be translated.”
At C:\Users\lab-jimw\Desktop\delete2008profile.ps1:16 char:32
+ $objuser = $objsid.Translate <<<< ([System.Security.Principal.NTAccount])
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
You cannot call a method on a null-valued expression.
At C:\Users\lab-jimw\Desktop\delete2008profile.ps1:17 char:39
+ $profilename = $objuser.value.split <<<< ("\")[1]
+ CategoryInfo : InvalidOperation: (split:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Failed to delete the profile, lab-jimw on 2008tester
Jim, is this something happening for any profile or just this one? If any profile on a windows 2008 server, then I suspect something problem with script. Otherwise, this profile may be special in someway or in use.
The script performs the translate method on ALL the SIDs found not just the SID you are trying to remove. If ANY of the SIDs found are bad you will get this error message.
You are most likely getting the error because one of the SIDs is no longer valid. (i.e the account was removed and that user no longer exists.)
Hmm, running it again with a couple accounts looks like the script deletes them (and reads “lab-test profile deleted successfully” but still gives the same error I mentioned before. Verified it actually did delete though so that’s good. I ended up looking elsewhere yesterday and piecing your script together with code described here: http://www.scriptlogic.com/smbit/article/manage-&-purge-local-windows-user-profiles . Here’s what I ended up with (probably needs to be cleaned up but it works well, the code at the bottom is to take ownership of and clear out our share holding the user’s roaming profile):
[cmdletbinding()]
param(
[parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$ComputerName = $env:computername,
[parameter(mandatory=$true)]
[string]$UserName
)
$Servers = get-content “c:\servers_2008.txt”
foreach($Server in $Servers) {
Write-host -ForegroundColor yellow “Checking on $Server for $Username profile”
if(Test-Connection -ComputerName $Server -Count 1 -ea 0) {
$UserProfile = Get-WmiObject Win32_UserProfile -Computer $Server -ea 0 -filter “localpath=’c:\\users\\$UserName'”
if (!$UserProfile) {
write-host -ForegroundColor gray “$Username not found on $Server”
}
else {
write-host -ForegroundColor green “Deleting $Username profile from $Server”
$UserProfile | Remove-WmiObject
}
}
}
$profilePath = get-item \\ProfilesServer\profiles\$Username*
$profilePath = “$profilePath”
write-host -ForegroundColor green “Removing $profilepath”
takeown /f $profilePath /r /d y
icacls $profilePath /grant administrators:F /t
Remove-Item -Path $profilePath -Recurse -Force
Thanks for your help.
Sorry to say that I an not a PowerShell wiz.. Can this script be automated to run with no results displayed. I would like to have it run in the background at startup so no one logging in sees anything. If this is possible can you help me by providing the working script to try.
Pete, you may want to use hstart,exe to trigger the script. Refer http://www.ntwind.com/software/hstart.html for details.
This is the 3rd method I’ve investigated to delete user profiles remotely. And all three methods fail intermittently when it comes to deleting the user’s AppData folder. I can delete them in Windows Explorer, remotely. But not through PowerShell. What’s different about AppData? Also I notice you have suppressed error messages. Any particular reason for that?
I haven’t seen this APPDATA deletion problem before. Is there any chance that contents of APPDATA were in use at the time of deletion?
I suppressed errors because, I have no interest in processing them given my environment. There other big reason behind it.
Hah! Found the answer in the comments here: http://www.minasi.com/forum/topic.asp?TOPIC_ID=37878
The problem with the “Application Data” folder is not that it is a junction, but that it is:
1) marked as Hidden and System
2) it has an ACL that denies everyone ReadData
I read the post, TJ and it is informative.
I prefer using the file(and registry) delete approach only when the WMI delete method fails(I never seen it happening). One must be cautious with file and registry delete method as this has the potential to make the user login with TEMP profile if the deletion is not proper.
If possible, I would like to address the problems with WMI delete method so that I can have one single approach which does ALL
when i used delprof for winxp, all was pretty simple two lines of code and boom the process started…i have 145 local user profiles to delete per computer…i can get the Get-Content c:\Scripts\ELCOMPLAB.txt to work…i can even get the Remove-UserProfile.ps1 to ask me for a username, but nothing happens…looks like my best bet is to buy a local profile tool to delete them…i have read over 40 forums about setting up powershell, batch files, delprof2, none of them worked at all, with little explanation on what variables do what, very frustrated…i need to know where i can learn about customizing powershell to do what i want to do…
I too used delprof2 and had little un satisfaction regarding a few options. Otherwise it is a good tool. I prefer the WMI method over delprof2 as I can handle the conditions I want.
Coming to your case, I am not sure what exactly you have used in powershell to delete the profiles remotely. But I am sure PS can do the task for you. If you would like to discuss further, please send me an email(http://techibee.com/contact-us) with complete details. I may be able to help you.
One of the big advantages of Delprof is deleting profiles by inactivity. WMI is already providing you the local path to the user profile — convert that to a UNC and read the lastwritten value from ntuser.dat (GI with -force). From there it is a short hop to a date delete.
Easier solution you can find if you try ” vtra Tsprofcleaner ” . It’s a great free software for servers and workstation profile cleaning .
You can use “tsprofcleaner” software to delete profiles . I think it’s easier 🙂
Thx, i modified it a little bit so it asks for a computer and username.
$computername=read-host ‘Enter computername’
$UserName=read-host ‘Enter username’
foreach($Computer in $ComputerName) {
Write-Verbose “Working on $Computer”
if(Test-Connection -ComputerName $Computer -Count 1 -ea 0) {
$Profiles = Get-WmiObject -Class Win32_UserProfile -Computer $Computer -ea 0
foreach ($profile in $profiles) {
$objSID = New-Object System.Security.Principal.SecurityIdentifier($profile.sid)
$objuser = $objsid.Translate([System.Security.Principal.NTAccount])
$profilename = $objuser.value.split(“\”)[1]
if($profilename -eq $UserName) {
$profilefound = $true
try {
$profile.delete()
Write-Host “$UserName profile deleted successfully on $Computer”
} catch {
Write-Host “Failed to delete the profile, $UserName on $Computer”
}
}
}
if(!$profilefound) {
write-Warning “No profiles found on $Computer with Name $UserName”
}
} else {
write-verbose “$Computer Not reachable”
}
}
Good script, thanks, i am working out that translate issue using the comments above. I just wanted to point out to everyone that there is a GPO setting for deleting unused profiles over a certain date. Just turn it on and poof, everything stays clean.
Also, this post is very successful and above all helpful! With the script, I could delete remote various profiles. Thank you Sitaram Pamarthi.
Hi,
is it working on windows 2008 i am getting error as “doesn’t contain method named ‘Delete'”
Hi,
is it working on windows 2008 server i am getting error as “doesn’t contain method named ‘Delete’”
Prasanna, This should work on Vista and above Operating systems
Hello There , Is there any paramether if i want remove all profiles at machine ?
Hi this script is perfect for my use, but I need to specify profiles that I need to NOT be cleaned, any ideas??
Regards
Chad
Hi
I am working in a library , but we use some laptop for student , and I want to write a script to delete the user profile at logoff. cause the students use the same user account to work
Thanks for your help
Hi, It seems that the script cannot accept wildcard. I would like to modify it to delete all the profiles except the logged one. would it be possible?
Valence, it is possible… try matching the profiles using -match
?? try matching the profiles using -match ??
What ? How? can u b more specific?