+ Post New Thread
Page 1 of 2 12 LastLast
Results 1 to 15 of 30
Scripts Thread, Remove AD users and home drives in Coding and Web Development; Hello, Does anyone know if it is possible to delete active directory users and their home drive. We have alot ...
  1. #1

    Join Date
    Nov 2010
    Location
    Birmingham
    Posts
    79
    Thank Post
    13
    Thanked 8 Times in 8 Posts
    Rep Power
    9

    Remove AD users and home drives

    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

  2. #2
    old_n07's Avatar
    Join Date
    Jun 2012
    Location
    North Staffordshire
    Posts
    99
    Thank Post
    10
    Thanked 17 Times in 15 Posts
    Rep Power
    7
    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.

    Code:
    $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

  3. #3

    Join Date
    Nov 2010
    Location
    Birmingham
    Posts
    79
    Thank Post
    13
    Thanked 8 Times in 8 Posts
    Rep Power
    9
    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

  4. #4
    old_n07's Avatar
    Join Date
    Jun 2012
    Location
    North Staffordshire
    Posts
    99
    Thank Post
    10
    Thanked 17 Times in 15 Posts
    Rep Power
    7
    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.

    Code:
    $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, delete line if not needed                             
                                
                                Remove-ADUser -Identity $_.samaccountname -Confirm:$false ## delete user account from AD

  5. #5
    jaminben's Avatar
    Join Date
    Oct 2012
    Location
    Norfolk
    Posts
    301
    Thank Post
    64
    Thanked 27 Times in 26 Posts
    Rep Power
    13
    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

    Code:
    $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).

    Code:
    $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")
    Last edited by jaminben; 7th October 2013 at 07:21 PM.

  6. #6
    old_n07's Avatar
    Join Date
    Jun 2012
    Location
    North Staffordshire
    Posts
    99
    Thank Post
    10
    Thanked 17 Times in 15 Posts
    Rep Power
    7
    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:

    Code:
    $users = Search-ADAccount -AccountDisabled -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
    Last edited by old_n07; 8th October 2013 at 07:50 AM.

  7. #7

    Join Date
    Jul 2010
    Posts
    578
    Thank Post
    67
    Thanked 26 Times in 21 Posts
    Rep Power
    14
    OK So Im Testing this code
    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
    Code:
    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?

  8. #8
    jaminben's Avatar
    Join Date
    Oct 2012
    Location
    Norfolk
    Posts
    301
    Thank Post
    64
    Thanked 27 Times in 26 Posts
    Rep Power
    13
    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.

  9. #9

    Join Date
    Jul 2010
    Posts
    578
    Thank Post
    67
    Thanked 26 Times in 21 Posts
    Rep Power
    14
    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.

  10. #10
    jaminben's Avatar
    Join Date
    Oct 2012
    Location
    Norfolk
    Posts
    301
    Thank Post
    64
    Thanked 27 Times in 26 Posts
    Rep Power
    13
    Quote Originally Posted by MattDLEA View Post
    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.
    Last edited by jaminben; 25th July 2014 at 03:07 PM.

  11. #11

    Join Date
    Jul 2010
    Posts
    578
    Thank Post
    67
    Thanked 26 Times in 21 Posts
    Rep Power
    14
    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

  12. #12
    jaminben's Avatar
    Join Date
    Oct 2012
    Location
    Norfolk
    Posts
    301
    Thank Post
    64
    Thanked 27 Times in 26 Posts
    Rep Power
    13
    Quote Originally Posted by MattDLEA View Post
    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

  13. #13
    jaminben's Avatar
    Join Date
    Oct 2012
    Location
    Norfolk
    Posts
    301
    Thank Post
    64
    Thanked 27 Times in 26 Posts
    Rep Power
    13
    I haven't tried this out but I think the below may work:

    Code:
    $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")
    Last edited by jaminben; 25th July 2014 at 05:43 PM.

  14. #14

    Join Date
    Jul 2010
    Posts
    578
    Thank Post
    67
    Thanked 26 Times in 21 Posts
    Rep Power
    14
    Will try that @jaminben however I been hacking all afternoon and this works but is not as eligent as yours
    How to delete home directories profiles and then users from AD

  15. #15
    jaminben's Avatar
    Join Date
    Oct 2012
    Location
    Norfolk
    Posts
    301
    Thank Post
    64
    Thanked 27 Times in 26 Posts
    Rep Power
    13
    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

SHARE:
+ Post New Thread
Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 6
    Last Post: 31st July 2008, 03:25 PM
  2. GPO and Home Drives
    By faza in forum Wireless Networks
    Replies: 8
    Last Post: 21st April 2008, 11:28 AM
  3. Exchange AD users and computers
    By browolf in forum Windows
    Replies: 0
    Last Post: 4th December 2006, 10:59 AM
  4. Moving Shared Folders and Home Drives
    By secman in forum Windows
    Replies: 4
    Last Post: 31st August 2006, 08:23 PM
  5. Replies: 22
    Last Post: 15th May 2006, 10:50 AM

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •