Jump to content

Recommended Posts

Posted

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

Posted

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

Posted

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

Posted

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

Posted (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 by jaminben
Posted (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 :D

Edited by old_n07
  • 9 months later...
Posted

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?

Posted

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.
Posted

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.

Posted (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 by jaminben
Posted

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 :)

Posted (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 by jaminben
Posted

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 :)

  • 1 month later...
Posted

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

Posted

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.

Posted (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 by jaminben
  • Thanks 1
Posted

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

Posted (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 by jaminben
  • Thanks 1
Posted

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?

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 account

Sign in

Already have an account? Sign in here.

Sign In Now



×
×
  • Create New...