0

I have a network share on a Windows Server 2012 machine that is used to store all the user profile files (My Documents, Desktop, etc).

There are hundreds of old users I need to get rid of and I am going through them all one by one... first making the administrator the owner of all of the files for one user... then giving full control to all that user's files to the administrator... then deleting that user's files... then going to the next user.

This will take days.

There are many valid/current user files which I do not want to become the owner of or delete in this same directory also.

Is there any less time consuming way to delete specific folders in this network share?

Some sort of script that I can enter in all the old users and just let it do its thing for a few hours?

1

Sure, with PowerShell everything is possible! :-) This is an overall process for how this can be done.

You could start by reading the top folders/users you want to delete, from a CSV file with the commands Import-CSV $Filename | ForEach-Object.

For each top folder, in the ForEach block, you can then read all subfolders and files with Get-ChildItem -Recurse.

You can then have a second CSV file with the files or folders that should not be deleted, and for each file you loop through, you can read and compare against this file, if it shall be saved or deleted (after taking ownership).

0

I had to do it again so revisited this today, following suggestions from @PatrikN this is the powershell script I used:

Get-ChildItem C:\UserDocs |
    ForEach-Object {
        if (!(Get-ADUser -Filter "sAMAccountName -eq '$($_.Name)'")) {
            "$($_.Name) does not exist and is being deleted."
            takeown /a /r /d Y /f $_.FullName
            $Acl = Get-Acl $_.FullName
            $Acl.AddAccessRule(
                (New-Object System.Security.AccessControl.FileSystemAccessRule(
                    [System.Security.Principal.WindowsIdentity]::GetCurrent().Name,
                    "FullControl",
                    "ContainerInherit, ObjectInherit",
                    "None",
                    "Allow"
                ))
            )
            (Get-Item $_.FullName).SetAccessControl($Acl)
            Remove-Item -LiteralPath $_.FullName -Force -Recurse
        }
    }

I didn't end up using CSV files.

The script loops through all user profile directories, queries if the name is in active directory, if not: take ownership, set full permissions, then delete. It worked well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.