topbanner_forum
  *

avatar image

Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
  • April 21, 2018, 02:32 PM
  • Proudly celebrating 13 years online.
  • Donate now to become a lifetime supporting member of the site and get a non-expiring license key for all of our programs.
  • donate

Author Topic: Script to set read+write permissions to folders for users based on foldername  (Read 422 times)

questorfla

  • Supporting Member
  • Joined in 2012
  • **
  • Posts: 530
  • Fighting Slime all the Time
    • View Profile
    • Donate to Member
We have  system that hosts a folder where every employee has a sub-folder for their private use that is named the same as their username for that system.  There have been a couple of times when those rights "per user" get removed.  The folders are fine, the admin access is fine.  But the user who stores files in that folder loses all rights to it for both read and write.  I believe this might be tied to a special archive program that runs every 3 months but i have to track it down.

It wondered if there was a way to walk the directory and read the name of each sub-folder within and Add read/write share permissions for each folder to the user with the same name as the folder.

The main folder named "employees" has sub-folders named johnsmith,   fredwilson,   maryjones,  etc. for about 40 - 50 users
The last two times it happened, i went through the list one by one and restored the read/write permissions.  Since the folder names are the exact same as the user names (no spaces) I was hoping there would be a way to walk through the sub-folders under "Employees" and add read/write permissions for each folder to the user with the same name as the folder.   The User named "johnsmith" would get read/write only to his sub-folder named "johnsmith".  Same for "fredwilson" and "maryjones"
Below is an example layout.

C:\Employees\
                      fredwilson
                      johnsmith
                      maryjones

There are no loose files in the Employees folder and no folders that do not belong to Users that have an account on that system.  I just wondered is there was a way to handle the issue programmatically when it occurs > Read in the name of the folder and add  read/write permissions for that folder to the user with that name.

Would prefer Powershell or batch but whatever works :)  I am sure it will be some variation of the "icacls" command.

icacls C:\employees\%user% /grant %user%:(F)

But I am not sure if this is even close as i seldom if ever use icacls






Ath

  • Supporting Member
  • Joined in 2006
  • **
  • Posts: 3,145
    • View Profile
    • Donate to Member
tl;dr;
You really should get the cause fixed, not clean up the mess afterward.

4wd

  • Supporting Member
  • Joined in 2006
  • **
  • Posts: 4,799
    • View Profile
    • Donate to Member
tl;dr;
You really should get the cause fixed, not clean up the mess afterward.

That's not the way the world works.

wraith808

  • Supporting Member
  • Joined in 2006
  • **
  • default avatar
  • Posts: 9,321
    • View Profile
    • Donate to Member
tl;dr;
You really should get the cause fixed, not clean up the mess afterward.

That's not the way the world works.

Especially not when someone else is paying you.  :-\ :huh: ;D

4wd

  • Supporting Member
  • Joined in 2006
  • **
  • Posts: 4,799
    • View Profile
    • Donate to Member
Open a PowerShell console with Admin rights.

Install the PowerShell NTFS Security module from the PowerShell Gallery as per here.

EDIT: If you want to mark the PowerShell Gallery as a Trusted repository, (it's run by Microsoft), open a PoSh console as Admin and enter the following:

Code: PowerShell [Select]
  1. Set-PSRepository -Name PSGallery -InstallationPolicy Trusted

PoSh will no longer complain about modules installed from it being non-signed.

Set2Rights.ps1
Code: PowerShell [Select]
  1. $source = 'C:\Employees'
  2. get-childitem -Path $source -Directory -Name | % { Add-NTFSAccess -Path "$source\$_" -Account "$env:computername\$_" -AccessRights FullControl }

If you don't want them to have full control of their directory, change FullControl to any of the following, multiple terms to be comma separated:

AppendData, ChangePermissions, CreateDirectories, CreateFiles, Delete, DeleteSubdirectoriesAndFiles, ExecuteFile, FullControl, GenericAll, GenericExecute, GenericRead, GenericWrite, ListDirectory, Modify, None, Read, ReadAndExecute, ReadAttributes, ReadData, ReadExtendedAttributes, ReadPermissions, Synchronize, TakeOwnership, Traverse, Write, WriteAttributes, WriteExtendedAttributes

NOTE: OK, I got un-lazy and tested it, couple of typos but it worked.

You'll need to create a shortcut and add options to bypass Policy Control, set the following as Target, (change path to file to suit), and set the Run as admin option, (under Advanced).

powershell.exe -executionpolicy bypass -File "<full path>\Set2Rights.ps1"

Or if running from a CLI/PoSh, (as Admin):

powershell.exe -executionpolicy bypass -File "<full path>\Set2Rights.ps1"
« Last Edit: April 03, 2018, 10:04 PM by 4wd »

questorfla

  • Supporting Member
  • Joined in 2012
  • **
  • Posts: 530
  • Fighting Slime all the Time
    • View Profile
    • Donate to Member
ATH:  I am open to suggestions on how to prevent this in the first place.  I am not even 100% sure the Archive utility is to blame because the timing of the problem is not really synced to the running of the Archive program.  I have considered other options such as Windows 10 updates which get blamed for everything from toe fungus to sunspots  :o and I feel sure adding the ability to remove user access from shared folders would fall right in line there somewhere.   :Thmbsup:
To be honest, i do have an ulterior motive for looking for a command-line method of doing this. 
Every time a new person is hired, there are a number of identical tasks that have to be performed using that new persons name and assigned password.  It had occurred to me that I could probably set up a master script to perform what now takes about 30 minutes per new hire and get that down to maybe one minute if everything could be scripted. 
Part of that process involves creating these folders and providing the correct information for ownership and sharing access.  Knowing how to do it from command line won't get me a raise or make more money, but if the script could do it all,  I would have an additional 29 minutes to play League of Legends every time they hired someone new. 8)

Flatop0315

  • Supporting Member
  • Joined in 2008
  • **
  • Posts: 14
    • View Profile
    • Donate to Member
questorfla,

This code should do what you are looking for, at least it works for me.

Code: PowerShell [Select]
  1. $source = 'C:\Employees'
  2. foreach ($i in get-childitem -Path $source -Directory -Name )
  3. {
  4. # This section sets the Permissions on each subfolder found in the parent folder
  5. $Acl = (Get-Item "C:\Employees\$i").GetAccessControl('Access')
  6. $Ar = New-Object System.Security.AccessControl.FileSystemAccessRule($i, 'Modify', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
  7. $Acl.SetAccessRule($Ar)
  8. Set-Acl -path "C:\Employees\$i" -AclObject $Acl
  9. }

questorfla

  • Supporting Member
  • Joined in 2012
  • **
  • Posts: 530
  • Fighting Slime all the Time
    • View Profile
    • Donate to Member
Thanks for the two replies.
4wd's, being the shortest would be nice but so far i can't get it to quite work.  I am sure i did something wrong with the new modules i had to import.  I saw it flash something in red but have not rerun
>  UPDATE  The error says:   add-NTFSAccess : The 'Add-NTFSAccess' command was found in the module 'NTFSSecurity', but the module could not be loaded.   So i am working on that one
>  Says something about the file not being digitally signed ;(  Also get further and just more messages telling me that for some reason the NTFSSecurity module is not going to run on this system ;((

PS:  I should add that this is a fully Up-to-date Windows 10 vr 1709 (Creator update installed) system, not Windows server and not Windows 10 1703.  That might make a difference.  Also the folders are accessed by the Users over the LAN in-house network, not directly from the system they are on.  All folders have the default shares of Admin as Owner.  The only thing i am trying to do is add each user to have access to their folder which is a folder named for them.  I normally add read/write for each user when i create the folders.  It is ONLY this one share permission that gets removed somehow on rare occasions.  The owner-share for admin is not changed when the other shares are removed.


Flatop0315.  On yours, i modified slightly making use of the $source variable you setup in line 1 and reused it in line 5 and 8 so this would be more universal and only need to state the folder-name once.  Thereafter using $source.  It appeared to work fine on a short test but did something i am not accustomed to for the sharing permissions. 
When i looked under the "Share" option it plainly says "not shared" so at first I thought the command had failed.

However, when i looked under the "Share" option for that folder it did show that user's name but with the permissions set to 'Contribute'. 
When i normally create these I don't even see that option.  I just click Share, add the username it is shared with and the permissions of  read/write. 
I noticed that the arrow beside 'contribute' would allow change to 'read/write'.  I tried to look up what the differences were and got even more confused. 
But the main worry is that even with that user listed, the folder does not show up as being shared at all.  Even when checking under Advanced system properties for all shared access.
PS: I did run the script under PowerShell as Admin

These folders serve as a backup for the employees desktop, documents and download files.  They are added to on a daily basis and while not perfect, have saved a few people from some major losses.

Any ideas on how to resolve this would be appreciated.  Perhaps i still did something wrong and i am continuing to test both versions



« Last Edit: April 03, 2018, 03:03 PM by questorfla »

Flatop0315

  • Supporting Member
  • Joined in 2008
  • **
  • Posts: 14
    • View Profile
    • Donate to Member
questorfla,

You can change 'modify' to 'Read,Write' in the code to only grant read/write permissions.  If you look under the Security tab for the folder, when you use modify in the code it gives the user additional permissions to Read & execute and list folder contents.  If you use 'Read,Write', then only those permission are set; however, when you go to share the folder, the permissions are now set to custom with the option to change it to read/write or read.  I imagine the custom setting is due to you modifying the permissions from the command line rather then through the GUI.

4wd

  • Supporting Member
  • Joined in 2006
  • **
  • Posts: 4,799
    • View Profile
    • Donate to Member
>I saw it flash something in red but have not rerun

You're just double-clicking on the file aren't you?

UPDATE  The error says:   add-NTFSAccess : The 'Add-NTFSAccess' command was found in the module 'NTFSSecurity', but the module could not be loaded.   So i am working on that one
>  Says something about the file not being digitally signed ;(  Also get further and just more messages telling me that for some reason the NTFSSecurity module is not going to run on this system ;((

You'll need to create a shortcut and add options to bypass Policy Control, set the following as Target, (change path to file to suit), and set the Run as admin option.

powershell.exe -executionpolicy bypass -File "<full path>\Set2Rights.ps1"

Or if running from a CLI/PoSh, (as Admin):

powershell.exe -executionpolicy bypass -File "<full path>\Set2Rights.ps1"

NOTE: Have updated the original post/script, now tested (had a couple of typos) also added info on how to Trust the PowerShell Gallery repository, (any modules from there will inherit the trust), and added the above execution info.
« Last Edit: April 04, 2018, 07:06 AM by 4wd »