Jump to content

Powershell Script to Remove Home directories in an OU


Recommended Posts

Posted

Dear All,

 

Found this little beauty when googling the other day. Our users are moved (by Salamander AD Sync) to their own OU when disabled on leaving, as it is very rare that you have to delete an entire Directory on the server for the whole year group, I found this script, which you can run before you delete the users, which will remove their home directories for you.

 

Get-ADuser -filter 'enabled -eq $false' -properties Name, homedirectory -SearchBase 'OU=this,OU=needs,OU=to,OU=be,DC=changed,DC=for,DC=you' |
   ForEach-Object {
       Write-Host ("Removing homedir for:" +$_.Name + ",path:" + $_.homedirectory)
       Remove-Item -Path $_.homedirectory -Force -Recurse
       }

  • Thanks 2
  • 2 weeks later...
Posted

Just for any novice to PowerShell or AD using this, I would personally comment out the Remove-Item line (put a # at the start of it) so you just get a bunch of write hosts saying what it was going to do, that way if you see a bunch of directories you were not expecting you pointed it at the wrong OU :)

 

Other than that, thanks for sharing BKGarry :)

Posted
Just for any novice to PowerShell or AD using this, I would personally comment out the Remove-Item line (put a # at the start of it) so you just get a bunch of write hosts saying what it was going to do

Remove-Item also supports the -WhatIf parameter which would prevent it from deleting files (PowerShell will just show what would happen).

 

Get-ADuser -filter 'enabled -eq $false' -properties Name, homedirectory -SearchBase 'OU=this,OU=needs,OU=to,OU=be,DC=changed,DC=for,DC=you' |
ForEach-Object {
   Write-Host ("Removing homedir for:" + $_.Name + ",path:" + $_.homedirectory)
   Remove-Item -Path $_.homedirectory -Force -Recurse [color="#FF0000"]-WhatIf[/color]
}

 

I would also change the Write-Host to Write-Output. ;)

Posted
I am all for Write-Output as you can actually do something with the output! Unless you are all running your scripts interactively? Also a try catch block so you can do some error trapping and propper logging would be good as well.

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