Skip to content

Instantly share code, notes, and snippets.

@micmaher
Created March 24, 2016 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micmaher/afcdc1dfc7b0e338ad30 to your computer and use it in GitHub Desktop.
Save micmaher/afcdc1dfc7b0e338ad30 to your computer and use it in GitHub Desktop.
Remove Old home Directories
<######################################################################################
.AUTHOR
Michael Maher
.DATE
14/01/16
.NOTE
Removes old home drives
#######################################################################################>
#region Variables
$deletedUsers = get-content "c:\scripts\mDelete.txt"
$dfsRoot = "\\FILESERVER\h"
$driveRoots = @("c:\dfsroots\h", "e:\home", "f:\home", "g:\home", "h:\home", "i:\home", "j:\home")
$domain = "IE"
$homeShare = "Home"
$right="FullControl"
$owner = "Desktop Admins" # Used for take ownership
#endregion
foreach ($user in $deletedUsers){
#### Step 1 Delete DFS Link
Write-Verbose "Checking if $user exists in $dfsRoot"
$dfsFolderPath = "$($dfsRoot)\$($user)"
If ($dfsFolderPath -eq $dfsRoot){Write-Verbose "Would delete $dfsRoot - script will terminate"; exit}
If ($dfsFolderPath -notlike "*$($user)*"){Write-Verbose "The username $user not found in $hDrivePath - script will terminate"; exit}
If(Test-path -pathtype Container $dfsFolderPath) {dfsutil link remove $dfsFolderPath; Write-Verbose "Removed $($dfsFolderPath)"}
#### Step 2 Find Home Directory on File System, Take Ownership and Delete
Write-Verbose "Look for H drives on File System"
Foreach ($folderRoot in $driveRoots){
$hDrivePath = "$($folderRoot)\$($user)"
# Safety Checks
If ($folderRoot -eq $hDrivePath){Write-Verbose "Would delete $folderRoot - script will terminate"; exit}
If ($hDrivePath -notlike "*$($user)*"){Write-Verbose "The username $user not found in $hDrivePath - script will terminate"; exit}
# Take Ownership
If(Test-path -pathtype Container $hDrivePath) {
Write-Verbose "Found $hDrivePath"
Try{
$rule=new-object System.Security.AccessControl.FileSystemAccessRule($owner, $Right, "ContainerInherit, ObjectInherit", "None", "Allow")
$acl=get-acl $hDrivePath
$acl.SetAccessRule($rule)
set-acl $hDrivePath $acl
Write-Verbose "Take control of $hDrivePath"}
Catch{If ($logging){Write-Verbose $error[0].ToString() + $error[0].InvocationInfo.PositionMessage}}
remove-item $hDrivePath -recurse -force; Write-Verbose "Removed $hDrivePath"
}
Else{Write-Verbose "$hDrivePath does not exist"}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment