none
Script to automate change of folder permissions and ownership based on the name of the folder?

    Question

  • Can this be done the way I specify below? If so, can someone post an example of a script that would work?

    2 directory structures need to be modified


    \\server\documents\%username% 
    \\server\userprofiles\%username%


    Take ownership of folders saved below \\server\documents\ and below \\server\userprofiles\ and all the files and subfolders contained inside
    Grant administrators full control to all these folders and the files and subfolders inside
    Add these permissions to those folders and contents

    Foldername(the name of the folder is %username% set to Full Control
    local sytstem set to full control
    administrators set to full control
    change owner of folder and its contents to foldername

    It must be able to handle errors such as not being able to find a valid username that matches the name of ther folder (typo in hand created folder or if the folder name is based on a user account that no longer exists etc.). In that case write a log listing folders where it could not set permissions. 
    If some files inside folders are locked/in use by user and that prevents changing permissions, skip those files and continue. List is separate log file so we can contact the user and rerun script while they are logged out.


    Most users in this domain stay logged in constantly other than to reboot even when they are not using the PC so they don't have to reopen all their documents and applications every morning when they start.  Can permissions be modified while the files are in use by the user (assuming the permssion change is not one that removes their permission to read and modify those open files)?


    • Edited by MyGposts Saturday, March 10, 2012 7:29 PM
    Saturday, March 10, 2012 7:28 PM

Answers

  •  

    There is no pre-defined script that can do what you ask.

    SubInAcl is the tool that is designed for this purpose and one of the only tools that can set owner on an object as well as alter/add permission sets easily.

    You could use a for loop in a batch file to drive the tool from a listing or file of names.  In all cases you will have to develop the script/batch to your needs.

    Start be reviewing how SubInAcl works and test it to see that you understand how it works.

    Again - there is no way in pure script to set the owner of a file or folder.  There is a tool in the RK called SetOwner that can do this.  You would need to discover the owner of the folder by some mechanism and feed it to the tool.

    Windows security is designed to allow anyone with 'Full Control' to take ownership of the object.  The design does not allow for giving ownership although an administrator with hat right can set the owner.

    You also need to define and determine how to correctly set the propagation and inheritance flags.  The root cause should be set first and then the folder in question need to be 'taken' by th administrator and then the Admins set as FullControl.  Set/update propagation flags throughout to the correct setting. Lastly add the owner and set owner.

    The last time I did a fix like this it took me around 5 passes before all folders were able to be set correctly.  There was no easy way to script it. 

    In many cases it may be easier to do a backup of the files.  recreate the folders correctly then reload the backup without security.  This will cause the new root security to be propagated to the newly restored files.

    In all cases you will have to analyze your situation and come up with a correct plane for th fix.  There is no magic script that will match all scenarios.  This is where you get to show your bosses why they need a trained administrator.  This is not an end user download an iPad app to get it done situation. You can use a script but you will have to write the script.

    Post back with specific questions after you have reviewed SubInAcl/SetOwner/CACLS and have decided how a script might help to automate those tools in your case.


    ¯\_(ツ)_/¯

    Saturday, March 10, 2012 9:59 PM

All replies

  • One more thing.  If that is too complicated,  maybe a script that lets us modify permissions on one user's profile folder or documents folder at a time.  It could just prompt for the path to the directory, take ownership if needed, set the administrator and local system permissions and then prompt for the user name that will be granted both full control and owner permissions, set those permissions and then ask if you want to do this again for another folder and user or quit.
    Saturday, March 10, 2012 7:50 PM
  • This is not a scripting issue.  It is an OS administrative issue and should be posted in the OS forum.

    This nearly always caused because the user shared folders are not set up correctly to begin with. Troubleshooting and fixing this needs to be done at the server where the files are located.  It may take considerable analysis and planning to come up with a correct fix.

    Note that you cannot 'set ownership' with a script. You can use SubInAcl to setowner and add the admin group.

    If  this is managed under Group Policy then you will need to work with your system administrators to resolve the issues.

    This should be moved to the Windows Server Forum.


    ¯\_(ツ)_/¯

    Saturday, March 10, 2012 9:01 PM
  •  It's true that the folder permissions "should have" been set up correctly, but they were not.  The original issue has been found and has been corrected for future users, but 90% are pre-existing folders with incorrect permissions.  The troubleshooting part has already been competed.  At this point, the damage needs to be corrected and a script would be a solution that would be much more efficient than doing it all by hand for all these folders.

    Why can't a script be used to automate using the tools or cryptic command line typing that changes ownership and set permissions?



    • Edited by MyGposts Saturday, March 10, 2012 9:21 PM
    Saturday, March 10, 2012 9:18 PM
  •  

    There is no pre-defined script that can do what you ask.

    SubInAcl is the tool that is designed for this purpose and one of the only tools that can set owner on an object as well as alter/add permission sets easily.

    You could use a for loop in a batch file to drive the tool from a listing or file of names.  In all cases you will have to develop the script/batch to your needs.

    Start be reviewing how SubInAcl works and test it to see that you understand how it works.

    Again - there is no way in pure script to set the owner of a file or folder.  There is a tool in the RK called SetOwner that can do this.  You would need to discover the owner of the folder by some mechanism and feed it to the tool.

    Windows security is designed to allow anyone with 'Full Control' to take ownership of the object.  The design does not allow for giving ownership although an administrator with hat right can set the owner.

    You also need to define and determine how to correctly set the propagation and inheritance flags.  The root cause should be set first and then the folder in question need to be 'taken' by th administrator and then the Admins set as FullControl.  Set/update propagation flags throughout to the correct setting. Lastly add the owner and set owner.

    The last time I did a fix like this it took me around 5 passes before all folders were able to be set correctly.  There was no easy way to script it. 

    In many cases it may be easier to do a backup of the files.  recreate the folders correctly then reload the backup without security.  This will cause the new root security to be propagated to the newly restored files.

    In all cases you will have to analyze your situation and come up with a correct plane for th fix.  There is no magic script that will match all scenarios.  This is where you get to show your bosses why they need a trained administrator.  This is not an end user download an iPad app to get it done situation. You can use a script but you will have to write the script.

    Post back with specific questions after you have reviewed SubInAcl/SetOwner/CACLS and have decided how a script might help to automate those tools in your case.


    ¯\_(ツ)_/¯

    Saturday, March 10, 2012 9:59 PM
  • Since I have seen the scenario of problems with incorrect permissions in roaming user profile folders and redirected documents folders found as the cause of folder redirection and roaming user policies failing  posted frequently in the Windows forums going back several years,  I know I am far from the first or last person who could use script like this.  The only thing unique about it is the actual server and share names that could easily be edited in a generic script since there is a recommended permission configuration should be the same for everyone for these particular folders.

    http://technet.microsoft.com/en-us/library/cc775853(v=ws.10).aspx

    Table 14 NTFS Permissions for Each Users Redirected Folder

     

    User Account Default Permissions Minimum permissions required

    %Username%

    Full Control, Owner Of Folder

    Full Control, Owner Of Folder

    Local System

    Full Control

    Full Control

    Administrators

    No Permissions

    No Permissions

    Everyone

    No Permissions

    No Permissions

    I would hope that everyone does not need to reinvent a new, unique script to do this.  Someone may have a script they have used in the past and can repost it.

    The idea of backing up and restoring with new permissions sounds interesting except that there would be too much data lost between the time the last backup and the restore since users are constantly editing documents in these folders.



    • Edited by MyGposts Saturday, March 10, 2012 10:27 PM
    Saturday, March 10, 2012 10:21 PM
  • Since I have seen the scenario of incorrect permissions in roaming user profile folders and redirected documents folders posted frequently in the Windows forums 'tback several years when these posters try to troubleshoot why it is working as expected,  I know I am far from the first or last person who could use script like this.  The only thing unique about it is the actual server and share names that could easily be edited in a generic script since there is a recommended permission configuration should be the same for everyone for these particular folders.

    http://technet.microsoft.com/en-us/library/cc775853(v=ws.10).aspx

    Table 14 NTFS Permissions for Each Users Redirected Folder

    User Account Default Permissions Minimum permissions required

    %Username%

    Full Control, Owner Of Folder

    Full Control, Owner Of Folder

    Local System

    Full Control

    Full Control

    Administrators

    No Permissions

    No Permissions

    Everyone

    No Permissions

    No Permissions

    I would hope that everyone does not need to reinvent a new, unique script to do this.  Someone may have a script they have used in the past and can repost it.

    The idea of backing up and restoring with new permissions sounds interesting except that there would be too much data lost between the the time the last backup and the restore since users are constantly editing documents in these folders.

    Unfortunte;y that is correct for a new folder.  TO remedy a broken folder is not that simpl.e

    First the share sis never and issue. 

    FOr shared folders we create as hare called something like 'User Shared Folders' ( which is the MIcrosopft default in most cases) the undelying folder has to have its' permissions set correctly so a shared folder can be autocreaed when teh system redirects a folder.  If the perms are correct then the settings you posted will be similar to waht teh system does.  On WS2003 and WS2008 these are slighly different and more general purpose settings like'CREATOR OWNER" are added.

    If  afolder has been created or atlered incorrectly then this has to be remedied.  If users have given othes permissions on the folders then you have an even bigge rheadache.

    If you just want to brut eforce a resolutuion then use SubInACL to take owner ship of all folders an files from teh share root down and add admins group with full permisisons.  set teh inheritance and propagation flags and remove all other ACEs.  This can be done with wild cards in SubInAcl.

    Afte ryu have esatblished a clean setup then just determine who the owner should be and use SubInAcl to set ownership of the users folder.  Everything else will be correct although you might want to add the WS2008 additions to the folders.  Again all of this can be done with wildcards.

    As I pointed out before. There is no pre-exisiting script to do this.  If you look in teh repository or search the web you might find something that is close that you could modify.  I would just use SubInAcl at the commandline.


    ¯\_(ツ)_/¯

    Saturday, March 10, 2012 10:34 PM
  • This script was posted on another forum

    @echo off
    :: Reset Home folder Permissions 
    :: RHP.cmd      +need admin rights to run correctly+ 
    :: change the permission based on the folder name adding  full control  to system and administrator too
    :: By gastone Canali
    setlocal
    set filename=%~n0
    title=%filename%
    set logfile="c:\admin\log\_%filename%.txt"
    set append2LOG=^>^> %logfile% 2^>^&1
    
    call :SET_HOME_PERMISSION "\\server\share"
    call :SET_HOME_PERMISSION "D:\users"
    
    
    goto :END
    
    :SET_HOME_PERMISSION
    pushD %1 || goto :ERR
    for /f "tokens=*" %%F in ('dir /b /a:d') do (
      net user "%%F" && (
            REM take ownership, to be able to change user folder permission
            takeown /F    "%%F\*.*"   /R /A /D y %append2LOG%
            REM FolderName is a Username then set user permission to Full  "%%F:F"
            REM user, administrator and system have Fulloontrol
            echo y|cacls  "%%F"  /c /T   /e  /g administrators:f system:f "%%F:F" %append2LOG%
      )||(
            REM take ownership, to be able to change user folder permission
            takeown /F    "%%F\*.*"   /R /A /D s %append2LOG%
            REM FolderName is NOT a Username only administrator and system have Fulloontrol
            echo y|cacls  "%%F"  /c /T   /e  /g administrators:F system:F %append2LOG% 
      )
    )  
    goto :EOF
    :ERR
    echo error: folder not found
    :END
    popd

    It kind of works, but has some problems when I tested it.

    1.  It modified every file in it's path (for example, if it was run from c:\, it would attempt to change every file on the C drive) instead of only the paths specified in the code.  

    2.  When I re-ran it from within the directory containing the folders I wanted to modify, it was able to add full control permissions to a user account with the same name as the folder, but failed to change change the owner to that user.

    3.  It errored at the end saying "popd" is not recognized as a valid command.

    Not sure abbout this part: 

    call :SET_HOME_PERMISSION "\\server\share"
    call :SET_HOME_PERMISSION "D:\users"
    

    Does it really need to be in the code twice as both a UNC share path and a local path?

    Any suggestions for fixes?

    Monday, March 12, 2012 1:45 AM
  • Why not just try running SubInAcl at the command line until you see how it works.  Once you understand how to get it to make the changes you need then put it in a batch file and call it in a loop.

    A quick looks tells nme that that script will not do what you need it to do unless the user already has full control of everything in the folder set.


    ¯\_(ツ)_/¯

    Monday, March 12, 2012 3:38 AM
  • From this site https://sites.google.com/site/powershellandphp/home-1

    If it looks hard to script it due to the use of built-in or extended Windows functions often Powershell is the way to go.

    ""

    Set folders ACL (owner and NTFS rights)

    This script set ACLs on all user home folders (user home folders name = user name) located on the network share \\server\homeroot. The script tasks are the following :
    • list user home folders
    • check if the username exists in AD
    • get current ACL
    • remove the security right Everyone Full Control
    • add builtin administrators with Full Control
    • add the user with Modify right and set the ownership on their folders
    The reference table flags of the object System.Security.AccessControl.FileSystemAccessRule is :
    Subfolders and Files only InheritanceFlags.ContainerInherit, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly
    This Folder, Subfolders and Files   InheritanceFlags.ContainerInherit, InheritanceFlags.ObjectInherit, PropagationFlags.None
    This Folder, Subfolders and Files InheritanceFlags.ContainerInherit, InheritanceFlags.ObjectInherit, PropagationFlags.NoPropagateInherit
    This folder and subfolders InheritanceFlags.ContainerInherit, PropagationFlags.None
    Subfolders only InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly
    This folder and files InheritanceFlags.ObjectInherit, PropagationFlags.None
    This folder and files InheritanceFlags.ObjectInherit, PropagationFlags.NoPropagateInherit

    Script:
    $rootfolder = Get-ChildItem -Path \\server\homeroot
    foreach ($userfolder in $rootfolder) {
            $userfolder.FullName
            If (get-qaduser "DOMAINNAME\$userfolder") {
                Get-Acl $userfolder.FullName | Format-List
                $acl = Get-Acl $userfolder.FullName
                $acl.SetAccessRuleProtection($True, $False)
                $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Everyone","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
                $acl.RemoveAccessRuleAll($rule)
                $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
                $acl.AddAccessRule($rule)
                $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($userfolder.Name,"Modify", "ContainerInherit, ObjectInherit", "None", "Allow")
                $acl.AddAccessRule($rule)
                $acct=New-Object System.Security.Principal.NTAccount("DOMAINNAME",$userfolder.name)
                $acl.SetOwner($acct)
                Set-Acl $userfolder.FullName $acl
                Get-Acl $userfolder.FullName  | Format-List
            }
    }
    Wednesday, September 05, 2012 12:23 PM
  • I might be late to the party but the following works if the folder name and the user name are the same. Tested on Windows 2008 Server.  Run from the file server in the directory where the folders for each user exists.

    Command line:

    FOR /F "tokens=*" %G IN ('dir /b') DO icacls %G /setowner %G /T


    Obviously this does not work for .V2 profile folders and would need a bit more tweaking to ignore the tail of the directory name.
    • Edited by JLeyow Thursday, November 28, 2013 5:26 PM
    Thursday, November 28, 2013 5:23 PM
  • Thanks for the script. This is PowerShell plus another add-on. "get-qaduser" is not standard.
    Friday, March 28, 2014 7:53 PM