Grant domain user/group privilege to folders recursively - powershell

Written below code to grant domain user privilege to folder in windows 2016. In output I can see that the user is added in folder permissions but did not add any permission though I mentioned to give full control access.
$rule=new-object System.Security.AccessControl.FileSystemAccessRule("domain\group","FullControl","Allow")
foreach ($file in $(Get-ChildItem "G:\usr" -recurse))
{
$acl=get-acl $file.FullName
$acl.SetAccessRule($rule)
set-acl $File.Fullname $acl
}

For recursive permissions you need to set ContainerInherit,ObjectInherit
Here is an example (Note it's not my code):
$Path = "C:\temp\New folder"
$Acl = (Get-Item $Path).GetAccessControl('Access')
$Username = "Domain\User"
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule($Username, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
$Acl.SetAccessRule($Ar)
Set-Acl -path $Path -AclObject $Acl
For more details take a look at http://www.tomsitpro.com/articles/powershell-manage-file-system-acl,2-837.html

Related

how to change specific folder permissions with powershell no GUI [duplicate]

I am trying to use the "default" options in applying folder permissions; by that, I mean that using the "Full Controll, Write, Read, etc" in the 'Properties' for a folder.
The following script works to add the user in, but it applies "Special Permissions" - not the ones with the tick boxes for the ones visible in the properties menu of the folder:
$Acl = Get-Acl "\\R9N2WRN\Share"
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule ("user","FullControl","Allow")
$Acl.SetAccessRule($Ar)
Set-Acl "\\R9N2WRN\Share" $Acl
What am I doing wrong please?
Specifying inheritance in the FileSystemAccessRule() constructor fixes this, as demonstrated by the modified code below (notice the two new constuctor parameters inserted between "FullControl" and "Allow").
$Acl = Get-Acl "\\R9N2WRN\Share"
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl "\\R9N2WRN\Share" $Acl
According to this topic
"when you create a FileSystemAccessRule the way you have, the
InheritanceFlags property is set to None. In the GUI, this
corresponds to an ACE with the Apply To box set to "This Folder Only",
and that type of entry has to be viewed through the Advanced
settings."
I have tested the modification and it works, but of course credit is due to the MVP posting the answer in that topic.
Referring to Gamaliel 's answer: $args is an array of the arguments that are passed into a script at runtime - as such cannot be used the way Gamaliel is using it.
This is actually working:
$myPath = 'C:\whatever.file'
# get actual Acl entry
$myAcl = Get-Acl "$myPath"
$myAclEntry = "Domain\User","FullControl","Allow"
$myAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($myAclEntry)
# prepare new Acl
$myAcl.SetAccessRule($myAccessRule)
$myAcl | Set-Acl "$MyPath"
# check if added entry present
Get-Acl "$myPath" | fl
Another example using PowerShell for set permissions (File / Directory) :
Verify permissions
Get-Acl "C:\file.txt" | fl *
Apply full permissions for everyone
$acl = Get-Acl "C:\file.txt"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("everyone","FullControl","Allow")
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "C:\file.txt"
Screenshots:
Hope this helps
In case you need to deal with a lot of folders containing subfolders and other recursive stuff. Small improvement on #Mike L'Angelo:
$mypath = "path_to_folder"
$myacl = Get-Acl $mypath
$myaclentry = "username","FullControl","Allow"
$myaccessrule = New-Object System.Security.AccessControl.FileSystemAccessRule($myaclentry)
$myacl.SetAccessRule($myaccessrule)
Get-ChildItem -Path "$mypath" -Recurse -Force | Set-Acl -AclObject $myacl -Verbose
Verbosity is optional in the last line
This One work for me
$path = "C:\test"
$name = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$acl = Get-Acl "C:\test"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($name,"FullControl","Allow")
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "C:\test"
Get-ChildItem -Path "$path" -Recurse -Force | Set-Acl -aclObject $acl -Verbose
$path = "C:\DemoFolder"
$acl = Get-Acl $path
$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$Attribs = $username, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"
$AccessRule = New-Object System.Security.AcessControl.FileSystemAccessRule($Attribs)
$acl.SetAccessRule($AccessRule)
$acl | Set-Acl $path
Get-ChildItem -Path "$path" -Recourse -Force | Set-Acl -aclObject $acl -Verbose

Powershell to set Read&Execute permission on a folder for Authenticated users

Im newbie in powershell and trying to figure out a way to set folder permissions for Authenticated Users. I want to remove all permissions for this user except Read&Execute.
I've tried to code below but it doesnt quite give the result I want:
$folder = 'C:\folder'
#remove inheritance
$acl = Get-ACL -Path $folder
$acl.SetAccessRuleProtection($True, $True)
Set-Acl -Path $folder -AclObject $acl
#set folder permissions to Read&Execute
$user = New-Object -TypeName 'System.Security.Principal.SecurityIdentifier' -ArgumentList #([System.Security.Principal.WellKnownSidType]::AuthenticatedUserSid, $null)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($user, "ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow")
$acl.SetAccessRule($rule)
Set-Acl -Path $folder -AclObject $acl

Take ownership of a folder and set inheritance with PowerShell

Attempting to set the owner of a folder as Domain Admins and force inheritance on all sub-folder/files. Using a combination of scripts I've found:
$Account = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList $DomainAdmins;
#Get a list of folders and files
$ItemList = Get-ChildItem -Path $Dir -Recurse;
#Iterate over files/folders
foreach ($Item in $ItemList) {
$Acl = $null; # Reset the $Acl variable to $null
$Acl = Get-Acl -Path $Item.FullName; # Get the ACL from the item
$Acl.SetOwner($Account); # Update the in-memory ACL
$isProtected = $false
$preserveInheritance = $false
$Acl.SetAccessRuleProtection($isProtected, $preserveInheritance)
Set-Acl -Path $Item.FullName -AclObject $Acl; # Set the updated ACL on the target item
}
Error: Set-Acl : Cannot bind argument to parameter 'AclObject' because it is null.
Some folders assign properly, however, not all. I suspect it breaks were there is no owner (possibly an account that's been removed from AD.)
Any ideas on how to approach this?
We will end up using this, even though it's not handling the long file paths correctly.
Import-Module -Name NTFSSecurity
#Remove Inheritance on user's root folder
Get-Item $UserRoot | Disable-NTFSAccessInheritance
#Add Domain Admin to user's root folder
Add-NTFSAccess -Path $UserRoot -Account 'BUILTIN\Administrators', 'yourDomain\Domain Admins' -AccessRights FullControl
#Set Inheritance on all sub-folders on user's directory
Get-ChildItem -Path $UserRoot -Recurse | Enable-NTFSAccessInheritance -PassThru
Check SetOwner() method for setting up owner for a folder
# Define the owner account/group
$Account = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList 'BUILTIN\Administrators';
# Get a list of folders and files
$ItemList = Get-ChildItem -Path c:\test -Recurse;
# Iterate over files/folders
foreach ($Item in $ItemList) {
$Acl = $null; # Reset the $Acl variable to $null
$Acl = Get-Acl -Path $Item.FullName; # Get the ACL from the item
$Acl.SetOwner($Account); # Update the in-memory ACL
Set-Acl -Path $Item.FullName -AclObject $Acl; # Set the updated ACL on the target item
}
Specify Inheritance in FileSystemAccessRule()
$Acl = Get-Acl "\\R9N2WRN\Share"
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl "\\R9N2WRN\Share" $Acl
Check the SO1 and SO2 for further related information.

"Set-Acl" not working when owner is not administrator

Getting the below error when trying to set permissions via PowerShell.
Set-Acl : The security identifier is not allowed to be the owner of this object.
I am trying to assign modify permission to folders and files within a folder recursively using PowerShell. The script works fine on folders where administrator is owner, but throws an error when the administrator is not owner:
$location = "E:\Data\Path_of_folder"
$group = "SecurityGroup_RW"
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule ($group, "Modify", "ContainerInherit,ObjectInherit", "None", "Allow")
$folders = Get-Childitem $location -Recurse | Where-Object {$_.PSISContainer}
foreach ($folder in $folders) {
$path = $folder.FullName
$acl = (Get-Item $path).GetAccessControl('Access')
$acl.SetAccessRule($rule)
Set-Acl $path $acl
}
I should be able to set the permissions for all folders, not just the folders for which Administrator is the owner.

Powershell script creating home folder for user and setting permissions

I am doing a powershell script which creates new domain user accounts in AD, and also creating home directories in the file server with relevant permissions.
My problem is I cannot get the permissions set.
In the code below, my_fileServer is the file server name; sso means single-sign-on id, which in the test code below is set to "user9999".
Any help is greatly appreciated!
Set-Variable homeDir -option Constant -value "\\my_fileServer\Users"
Set-Variable sso -option Constant -value "user9999"
# If the folder for the user does not exist, make a new one and set the correct permissions.
if ( (Test-Path "$homeDir\$sso") -eq $false)
{
try
{
$NewFolder = New-Item -Path $homeDir -Name $sso -ItemType "Directory"
$Rights = [System.Security.AccessControl.FileSystemRights]"FullControl,Modify,ReadAndExecute,ListDirectory,Read,Write"
$InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]::None
$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
$objType =[System.Security.AccessControl.AccessControlType]::Allow
$objUser = New-Object System.Security.Principal.NTAccount "my_full_domain_name\$sso"
$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule `
($objUser, $Rights, $InheritanceFlag, $PropagationFlag, $objType)
$ACL = get-acl -Path $NewFolder
$ACL.AddAccessRule($objACE)
$objReturn = Set-ACL -Path "$homeDir\$sso" -AclObject $ACL
$objReturn
}
catch
{
$msg = $_
$msg
}
}
The home folder gets created OK, but when I check the permissions for the user, no box is ticked.
The problem is your inhertiance. You are not allowing the permission to be inherited on subfolders and files(items he owns in his folder). That's why you don't see the permissions(only "Special Permission") in the basic security window. If you open "Advanced Security Settings" you will see that the user has full control OVER THIS folder, and not the contents. As long as you add permissions(with inheritance) for CREATOR OWNER so the owner get's access on to items, I think you'll be fine. However, you could fix it already now like this:
$InheritanceFlag = #([System.Security.AccessControl.InheritanceFlags]::ContainerInherit,[System.Security.AccessControl.InheritanceFlags]::ObjectInherit)
Unless there are special requirements, you should give users complete access over his folder(full inheritance). Full solution with fixed inheritance (I also cleaned up your Set-ACL path and removed unnecessary returnobject):
try
{
$NewFolder = New-Item -Path $homeDir -Name $sso -ItemType "Directory"
$Rights = [System.Security.AccessControl.FileSystemRights]"FullControl,Modify,ReadAndExecute,ListDirectory,Read,Write"
$InheritanceFlag = #([System.Security.AccessControl.InheritanceFlags]::ContainerInherit,[System.Security.AccessControl.InheritanceFlags]::ObjectInherit)
$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
$objType =[System.Security.AccessControl.AccessControlType]::Allow
$objUser = New-Object System.Security.Principal.NTAccount "my_full_domain_name\$sso"
$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule `
($objUser, $Rights, $InheritanceFlag, $PropagationFlag, $objType)
$ACL = Get-Acl -Path $NewFolder
$ACL.AddAccessRule($objACE)
Set-ACL -Path $NewFolder.FullName -AclObject $ACL
}
I sadly can't vote up, but I agree with both answers above(Graimer and C.B.), the actual answer is a combination of both.
- You need to check permissions in the "advanced" window
- Even though your code "works", without inheritance your users won't be able to do much in the folder you assign them.
All the permissions are correctly set as 'Special Permmissions', you can check clicking on Advanced and look at 'Authorization' tab.
Keep it simple, do it with less... What you missed is the SetAccessRuleProtection function.
Here's the code that will give you the ticks that you want.
if (-not (Test-Path "$homeDir\$sso"))
{
$acl = Get-Acl (New-Item -Path $homedir -Name $sso -ItemType Directory)
# Make sure access rules inherited from parent folders.
$acl.SetAccessRuleProtection($false, $true)
$ace = "$domain\$sso","FullControl", "ContainerInherit,ObjectInherit","None","Allow"
$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule($ace)
$acl.AddAccessRule($objACE)
Set-ACL -Path "$homeDir\$sso" -AclObject $acl
}