william_tropico Posted October 3, 2013 Posted October 3, 2013 Hello, Does anyone know if it is possible to delete active directory users and their home drive. We have alot of students who have left and want to easily delete the accounts and home directory's through a batch script. All the users to be deleted are in one OU if that helps? Thank you, William
old_n07 Posted October 3, 2013 Posted October 3, 2013 Not had chance to test it but this should suffice, you will need to edit the OU paths to match your AD structure and the servers in the remote connections if you are running remotely. $log = c:\logs\delete.txt #change location as necessary $error.Clear() $startupVariables ="" new-variable -force -name startupVariables -value ( Get-Variable | % { $_.Name } ) #gets initial variables present before script is run function Cleanup-Variables { Get-Variable | Where-Object { $startupVariables -notcontains $_.Name } | % { Remove-Variable -Name "$($_.Name)" -Force -Scope "global" }} function RemoteConnections{ Get-PSSession | Remove-PSSession #clear up old remote sessions #email session $script:Sessemail = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://email.yourdomain.ac.uk/PowerShell/ -Authentication Kerberos Import-PSSession $Sessemail #AD Session $script:SessDC02 = New-PSSession -computername DC.yourdomain.ac.uk -Authentication Kerberos Import-Module ActiveDirectory cls } RemoteConnections $users = Search-ADAccount -searchbase "OU=Delete users,DC=YourDomain,DC=AC,DC=UK" | ForEach-Object {get-aduser $_.samaccountname -Properties * | select samaccountname, HomeDirectory, profilepath} $users | ForEach-Object { $_.samaccountname | Out-File $log remove-item $_.homeDirectory -recurse -force ## delete home directory from server remove-item $_.profilepath -recurse -force ## delete profile folder from server, rem out if not needed Disable-Mailbox -Identity $_.samaccountname -Confirm:$false ## delete mailbox, rem out if not needed Remove-ADUser -Identity $_.samaccountname -Confirm:$false ## delete user account from AD } Get-PSSession | Remove-PSSession cleanup-variables HTH
william_tropico Posted October 4, 2013 Author Posted October 4, 2013 Not having much luck getting this to work. keeps throwing up errors of Parameter set cannot be resolved using the specified named parameters for Search-ADAccount. Set the domain and running the script as a domain admin. Thank you, William
old_n07 Posted October 4, 2013 Posted October 4, 2013 Are you running this directly on a DC? If you are then you only need this bit of code below, You need to edit the text in red to reflect the OU structure in your active directory to where the accounts are located. If you don't have profile directories then you can delete the line in blue. $users = Search-ADAccount -searchbase [color="#FF0000"]"OU=Delete users,DC=YourDomain,DC=AC,DC=UK"[/color] | ForEach-Object {get-aduser $_.samaccountname -Properties * | select samaccountname, HomeDirectory, profilepath} $users | ForEach-Object { $_.samaccountname | Out-File $log remove-item $_.homeDirectory -recurse -force ## delete home directory from server [color="#0000FF"] remove-item $_.profilepath -recurse -force ## delete profile folder from server, delete line if not needed [/color] Remove-ADUser -Identity $_.samaccountname -Confirm:$false ## delete user account from AD
jaminben Posted October 7, 2013 Posted October 7, 2013 (edited) Your missing a curly brace at the end.... } and you would also need to remove or specify your Out-File Nice piece of code though $users = Search-ADAccount -searchbase "OU=Delete users,DC=YourDomain,DC=AC,DC=UK" | ForEach-Object {get-aduser $_.samaccountname -Properties * | select samaccountname, HomeDirectory, profilepath} $users | ForEach-Object { remove-item $_.homeDirectory -recurse -force ## delete home directory from server remove-item $_.profilepath -recurse -force ## delete profile folder from server, delete line if not needed Remove-ADUser -Identity $_.samaccountname -Confirm:$false ## delete user account from AD } EDIT I couldn't actually get the above to work correctly so changed it around a bit... I've added some on screen logging so you can see what its going to do first then you can try it at your own risk (I've not tested it fully). $users = Get-ADUser -Filter "*" -SearchBase "OU=SomeOU,OU=SomeOtherOU,DC=jaminben,DC=local" -Properties samaccountname, HomeDirectory, profilepath $users | ForEach-Object { #delete user account from AD #Remove-ADUser -Identity $_.samaccountname -Confirm:$false <--- Uncomment if needed Write-Host 'SamAccountName: '$_.samaccountname #delete home directory from server #remove-item $_.homeDirectory -recurse -force <--- Uncomment if needed Write-Host 'Home Directory: '$_.homeDirectory #delete profile folder from server, delete line if not needed #remove-item $_.profilepath -recurse -force <--- Uncomment if needed Write-Host 'Profile Path: '$_.profilepath `n } Write-Host `n`n'Press any key to close...' $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") Edited October 7, 2013 by jaminben
old_n07 Posted October 8, 2013 Posted October 8, 2013 (edited) It appears that search-adaccount has some issues in PS 3 now in that it needs another parameter to work, if you disable the accounts to be deleted (if they aren't already) then this will work: $users = Search-ADAccount [color="#FF0000"]-AccountDisabled[/color] -searchbase "OU=Delete users,DC=YourDomain,DC=AC,DC=UK" | ForEach-Object {get-aduser $_.samaccountname -Properties * | select samaccountname, HomeDirectory, profilepath} It's a handy line anyway for searching for disabled accounts in the organisation anyway, search-adaccount can find locked, disabled expired or expiring accounts among other things. As you said Get-ADUser works just as well in this case though Edited October 8, 2013 by old_n07
MattDLEA Posted July 25, 2014 Posted July 25, 2014 OK So Im Testing this code $users = Get-ADUser -Filter "*" -SearchBase "OU=Class 2013,OU=Students,DC=School,DC=local" -Properties samaccountname, HomeDirectory, profilepath $users | ForEach-Object { #delete home directory from server remove-item $_.HomeDirectory -recurse -force Write-Host 'Home Directory: '$_.HomeDirectory #delete profile folder from server, delete line if not needed remove-item $_.profilepath -recurse -force Write-Host 'Profile Path: '$_.profilepath `n #delete user account from AD Remove-ADUser -Identity $_.samaccountname -Confirm:$false Write-Host 'SamAccountName: '$_.samaccountname } Profile Path is \\MainServer\Pro\%username% Home Path is \\MainServer\HomeFolders\%username% This is in a test environment so its safe to mess about. This script throws up errors. It does delete all the selected users from the AD it does not delete there profile or Home directories remove-item : Access to the path '\\MainServer\HomeFolders\cice\Documents' is denied. At C:\bin\Remove-Users.ps1:8 char:9 + remove-item $_.HomeDirectory -recurse -force + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (\\MainServer\HomeFolders\cice:String) [Remove-Item], UnauthorizedAccessException + FullyQualifiedErrorId : RemoveItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.RemoveItemCommand Home Directory: \\MainServer\HomeFolders\cice remove-item : Cannot find path '\\MainServer\Pro\cice' because it does not exist. At C:\bin\Remove-Users.ps1:12 char:9 + remove-item $_.profilepath -recurse -force + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (\\MainServer\Pro\cice:String) [Remove-Item], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand Profile Path: \\MainServer\Pro\cice SamAccountName: cice Any ideas?
jaminben Posted July 25, 2014 Posted July 25, 2014 Looks like you don't have permissions to delete the folders... does the user running the script have permissions to do this? remove-item : Access to the path '\\MainServer\HomeFolders\cice\Documents' is denied.
MattDLEA Posted July 25, 2014 Posted July 25, 2014 I am on the server using PowerShell as Administrator. I know if i do this manually I have to right click the profile then take ownership etc. I thought this would remove the need for that.
jaminben Posted July 25, 2014 Posted July 25, 2014 (edited) I know if i do this manually I have to right click the profile then take ownership etc. I think your issue is exactly that... you need to take ownership before you can delete. Try using power shell to take ownership... scripting guy has a good tutorial. I'm on my phone ATM so can't provide link. Edited July 25, 2014 by jaminben
MattDLEA Posted July 25, 2014 Posted July 25, 2014 Just Checked the script works for people who have not yet logged on. But once they have then I cant delete even the home folders as admin on the server. Will have a look but could you post a link when you get change just in case please
jaminben Posted July 25, 2014 Posted July 25, 2014 Will have a look but could you post a link when you get change just in case please Hey, Scripting Guy! How Can I Use Windows PowerShell to Determine the Owner of a File? - Hey, Scripting Guy! Blog - Site Home - TechNet Blogs
jaminben Posted July 25, 2014 Posted July 25, 2014 (edited) I haven't tried this out but I think the below may work: $users = Get-ADUser -Filter "*" -SearchBase "OU=Class 2013,OU=Students,DC=School,DC=local" -Properties samaccountname, HomeDirectory, profilepath #The user who will take ownership $objUser = New-Object System.Security.Principal.NTAccount("yourDomain", "Administrator") $users | ForEach-Object { #Get home directory object $objHomeDirectory = Get-Acl $_.HomeDirectory #Set home directory object ownership to new user $objHomeDirectory.SetOwner($objUser) #delete home directory from server remove-item $_.HomeDirectory -recurse -force Write-Host 'Home Directory: '$_.HomeDirectory #Get profile path object $objProfilePath = Get-Acl $_.profilepath #Set profile path object ownership to new user $objProfilePath.SetOwner($objUser) #delete profile folder from server, delete line if not needed remove-item $_.profilepath -recurse -force Write-Host 'Profile Path: '$_.profilepath `n #delete user account from AD #Remove-ADUser -Identity $_.samaccountname -Confirm:$false Write-Host 'SamAccountName: '$_.samaccountname } Write-Host "Press any key to continue..." $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") Edited July 25, 2014 by jaminben
MattDLEA Posted July 25, 2014 Posted July 25, 2014 Will try that @jaminben however I been hacking all afternoon and this works but is not as eligent as yours http://www.edugeek.net/forums/how-do-you-do/140029-how-delete-home-directories-profiles-then-users-ad.html#post1205503
jaminben Posted July 25, 2014 Posted July 25, 2014 I think your over complicating things by running different scripts to get the same data (paths) which you already had in the original script you posted. All you then need to do is change the ownership of those paths using the extra cmdlets and passing it your user who will take ownership. However if you understand your process and it works then its all good
ish Posted September 16, 2014 Posted September 16, 2014 Hi jaminben, im getting the following error when running the script, can you help/advise? Remove-Item : Cannot bind argument to parameter 'Path' because it is null. At C:\Users\Administrator\Desktop\Untitled4.ps1:10 char:16 + Remove-Item <<<< $user.HomeDirectory + CategoryInfo : InvalidData: ( [Remove-Item], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.RemoveItemCommand your help/advice would be much appreciated thanks ish
old_n07 Posted September 17, 2014 Posted September 17, 2014 Can you post up the code you are using, it may be just a simple typo 1
jaminben Posted September 17, 2014 Posted September 17, 2014 Can you also check to make sure the actual 'Home Directory' path exists... looks to me like its trying to bind the command to a path that doesn't exist. 1
ish Posted September 17, 2014 Posted September 17, 2014 Hi, here is the code: ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- $users = Get-ADUser -Filter "*" -SearchBase "OU=DELETE,DC=markaz-uloom,DC=ac,DC=uk" -Properties samaccountname, HomeDirectory, profilepath #The user who will take ownership $objUser = New-Object System.Security.Principal.NTAccount("markaz-uloom", "Administrator") $users | ForEach-Object { #Get home directory object $objHomeDirectory = Get-Acl $_.HomeDirectory #Set home directory object ownership to new user $objHomeDirectory.SetOwner($objUser) #delete home directory from server remove-item $_.HomeDirectory -recurse -force Write-Host 'Home Directory: '$_.HomeDirectory #Get profile path object $objProfilePath = Get-Acl $_.profilepath #Set profile path object ownership to new user $objProfilePath.SetOwner($objUser) #delete profile folder from server, delete line if not needed remove-item $_.profilepath -recurse -force Write-Host 'Profile Path: '$_.profilepath `n #delete user account from AD #Remove-ADUser -Identity $_.samaccountname -Confirm:$false #Write-Host 'SamAccountName: '$_.samaccountname } Write-Host "Press any key to continue..." $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") ------------------------------------------------------------------------------------------ I have checked 'Home Directory' and 'Profile Path' both exist.
jaminben Posted September 17, 2014 Posted September 17, 2014 (edited) Try commenting out everything in the For-Each loop except for the Write-Host and see what you get back... check to make sure it all looks valid. EDIT Or try replacing it with something like: $users | ForEach-Object { Write-Host 'Sam Account Name: '$_.samaccountname Write-Host 'Home Directory: '$_.HomeDirectory Write-Host 'Profile Path: '$_.profilepath } Edited September 17, 2014 by jaminben 1
ish Posted September 17, 2014 Posted September 17, 2014 this is what is returned: Home Directory: \\Svr\Data$\Students\blue\maryam Profile Path: \\Svr\Profile\Students\blue\maryam SamAccountName: maryam Press any key to continue... Exception calling "ReadKey" with "1" argument(s): "The method or operation is not implemented." At C:\Users\Administrator\Desktop\delteuserprofilehd.ps1:39 char:28 + $x = $host.UI.RawUI.ReadKey <<<< ("NoEcho,IncludeKeyDown") + CategoryInfo : NotSpecified: ( [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException
jaminben Posted September 17, 2014 Posted September 17, 2014 What version of PowerShell are you using? You can check with: $host.version 1
ish Posted September 17, 2014 Posted September 17, 2014 version 2? Major Minor Build Revision ----- ----- ----- -------- 2 0 -1 -1
jaminben Posted September 17, 2014 Posted September 17, 2014 (edited) Ok, I think your going to have to update to version >3... once updated rather than using the ISE create a something.txt file and rename it to something.ps1. Paste in the code from below > save it > right click the file and do "Run with Powershell". [color=#333333]Write-Host "Press any key to Close..."[/color] [color=#333333]$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") [/color] What do you get now? EDIT Once you've done that and if you don't get any errors try the below: $users = Get-ADUser -Filter "*" -SearchBase "OU=DELETE,DC=markaz-uloom,DC=ac,DC=uk" -Properties samaccountname, HomeDirectory, profilepath $users | ForEach-Object { Write-Host 'Sam Account Name: '$_.samaccountname Write-Host 'Home Directory: '$_.HomeDirectory Write-Host 'Profile Path: '$_.profilepath `n`n } Write-Host `n`n"Press any key to Close..." $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") If both those code blocks work you should be able to add in the other bits you need to carry out the original powershell task. Edited September 17, 2014 by jaminben 1
ish Posted September 17, 2014 Posted September 17, 2014 ok so i have updated to version 3. the first code ran ok, without any errors. when running the second code i get the following: Sam Account Name: maryam Home Directory: \\Svr-muloom\Data$\Students\blue\maryam Profile Path: \\Svr-muloom\Profiles\Students\blue\maryam Press any key to Close... Exception calling "ReadKey" with "1" argument(s): "The method or operation is not implemented." At line:15 char:1 + $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: ( [], MethodInvocationException + FullyQualifiedErrorId : NotImplementedException this only happens when executing via ise. when executing via a .ps1 script it runs without errors? any ideas? - - - Updated - - - ok so i have updated to version 3. the first code ran ok, without any errors. when running the second code i get the following: Sam Account Name: maryam Home Directory: \\Svr-muloom\Data$\Students\blue\maryam Profile Path: \\Svr-muloom\Profiles\Students\blue\maryam Press any key to Close... Exception calling "ReadKey" with "1" argument(s): "The method or operation is not implemented." At line:15 char:1 + $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: ( [], MethodInvocationException + FullyQualifiedErrorId : NotImplementedException this only happens when executing via ise. when executing via a .ps1 script it runs without errors? any ideas?
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now