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.
Related
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
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
I am writing a PowerShell script which would delete a specific user from all sub-directories.
Below script only removes the permission from the folder but I want to remove permission from all sub-folders as well.
$acl = get-acl c:\temp
$accessrule = New-Object System.Security.AccessControl.FileSystemAccessRule ("domain\user","Read",,,"Allow")
$acl.RemoveAccessRuleAll($accessrule)
Set-Acl -Path "c:\temp" -AclObject $acl
You are only setting the acl of the root folder. Set-Acl by itself does not allow you to propagate to subfolders.
Note that that might not be what you want anyway. You want to remove a rule from all folders instead of replacing the acls on all subfolders with the acl of your root folder.
Safer would be to get the acl of each subfolder, remove the rule and set the acl of each subfolder.
icaclscudo's to Ansgar might be better for this task. A Powershell way might be as follows
$accessrule = New-Object system.security.AccessControl.FileSystemAccessRule("domain\user","Read",,,"Allow")
$root = 'c:\temp'
#(Get-Item $root) + #(Get-ChildItem $root -Recurse -Directory) | Foreach-Object {
$acl = Get-Acl $_.FullName
$acl.RemoveAccessRuleAll($accessrule)
Set-Acl $_.FullName -AclObject $acl -WhatIf
}
$Path = "c:\temp\"
$User = "admin"
$Account = new-object system.security.principal.ntaccount($User)
$ACL = Get-Acl -path $Path
$ACL.PurgeAccessRules($Account)
$ACL | Set-Acl -path $Path -Verbose
gci -Recurse -Path $Path -Directory | %{
$ACL = Get-Acl -path $_.FullName
$ACL.PurgeAccessRules($Account)
$ACL | Set-Acl -path $_.FullName -Verbose
}
I need a group to not be able to modify(/delete) a root folder but the same group has to be able to modify all the subfolders and files, using powershell (repetition/volume)
nb. end result should be two acl rules:
1. one for the current folder (readonly, can make subfolders , can delete subfolders but cannot delete root folder).
2. a second rule for the subfolders and files, in which they can delete and create and have free range over
I have a series of powershell codes that adds the ACL rule for both situations (seperately)
#subfolder rights
$existingAcl = Get-Acl -Path $pad
$permissions = $rechtendoel,'ExecuteFile,ReadData,ReadAttributes,ReadExtendedAttributes,CreateFiles,AppendData,WriteAttributes,WriteExtendedAttributes,DeleteSubdirectoriesAndFiles,Delete,ReadPermissions', 'ContainerInherit,ObjectInherit', 'InheritOnly', 'Allow'
$regel= New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permissions
$existingAcl.SetAccessRule($regel)
$existingAcl | Set-Acl -Path $pad
#rights for just the folder
$existingAcl2 = Get-Acl -Path $pad
$rechten2 = $rechtendoel,'ExecuteFile,ReadData,ReadAttributes,ReadExtendedAttributes,CreateFiles,AppendData,WriteAttributes,WriteExtendedAttributes,DeleteSubdirectoriesAndFiles,ReadPermissions', 'None', 'None', 'Allow'
$regel2= New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $rechten2
$existingAcl2.SetAccessRule($regel2)
$existingAcl2 | Set-Acl -Path $pad
However when I run both in succession (or seperate from eachother) the latter run segment overwrites the earlier rule.
Try using this type of method for items in sub-directories
$NewAcl = Get-Acl File0.txt
Get-ChildItem -Path "C:\temp" -Recurse -Include "*.txt" -Force | Set-Acl -AclObject $NewAcl
Reference
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.security/set-acl?view=powershell-6
I would like to do something similar to How to Remove all permissions for a specific user?, but I want to remove all access to the file for everybody except the owner of the file.
Is it possible to do that in a relatively clean way?
I suppose I could call get-acl C:\users\myusername\AppData\Local\Temp\TheFile.txt and then walk through all the users listed there, and remove all rights for each one (as described in the linked question above), but is there an easier way?
Examplecode in a function (Put it simply in the same Scriptfile, above all your own code):
function Remove-ACLEntries
{
[CmdletBinding()]
param(
[string]$File
)
$authusers = ((New-Object System.Security.Principal.SecurityIdentifier 'S-1-5-11').Translate([System.Security.Principal.NTAccount])).Value
$acl = Get-Acl $File
$acl.SetAccessRuleProtection($True, $False)
$owner = $acl.owner;
For($i=$acl.Access.Count - 1; $i -gt 0; $i--)
{
$rule = $acl.Access[$i]
if ($rule.IdentityReference -ne $owner -or $rule.IdentityReference -eq $authusers)
{
$acl.RemoveAccessRule($rule)
}
}
Set-ACL -Path $file -AclObject $acl | Out-Null
}
Usage Single File:
Remove-ACLEntries -File c:\your\path\to\file.txt
Usage Multiple Files:
$files = Get-Childitem c:\your\path -Recurse
foreach ($file in $files){ Remove-ACLEntries -File $file.Fullname }
Attention: The User you are using to operate this function must have fullaccess to the file by himself. If the function don't working, try to run the powershell in Adminmode.
Greetings, Ronny
The example below removes all the ACLs and sets the ACL to allow Full Control for the owner of the file.
$acl = Get-Acl "$filePath"
$object = New-Object System.Security.Principal.Ntaccount($acl.owner)
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($acl.owner,"FullControl","Allow")
$acl.SetOwner($object)
$acl.SetAccessRuleProtection($true,$false)
$acl.SetAccessRule($AccessRule)
#$acl.SetAccessRule($sysUserAccessRule)
$acl | Set-Acl "$filePath"