Script to remove user profiles / Ad accounts and Home Directory

Associate
Joined
19 Jul 2006
Posts
1,847
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

This is on a Windows 2012 Server with win 7/8 clients.
The Profile appears in the folder as cice.v2 if that makes any difference.
I have also set up folder redirects so that the documents and pictures redirect to the homefolder
 
Running the script as administrator on directly on the server.
However looking into it I cant delete the folders manually with out right clicking and taking ownership of them :(

Is there a way to code that into the script?
 
Back
Top Bottom