I'm trying to write a script that can remove access rights for just one (e.g. Everyone) on folders that have inherited permissions in place.
The other inherit permissions should stay intact. I can remove the inherit permissions and then remove access for that group, but inheritance is then broken. I don't want to enable inheritance after this action because of subfolders having no inheritance being broken.
How do I just remove this group without messing with the rest of the permissions?
You cannot (by design) remove an inherited permission, "without messing with the rest of the permissions".
What you can do is
Disallow inheritance, but preserve already inherited rules
Remove/modify the EVERYONE ACE after removing inheritance
Like this:
$FilePath = "C:\parentFolder\childItem.ext"
$FileACL = Get-Acl $FilePath
# Remove inheritance but preserve existing entries
$FileACL.SetAccessRuleProtection($true,$true)
Set-Acl $FilePath -AclObject $FileACL
# Retrieve new explicit set of permissions
$FileACL = Get-Acl $FilePath
# Retrieve "everyone" rule
$EveryoneRule = $FileACL.GetAccessRules($true,$true,[System.Security.Principal.NTAccount]) | Where-Object {$_.IdentityReference -eq [System.Security.Principal.NTAccount]"EVERYONE"}
# Remove it - or modify it and use SetAccessRule() instead
$FileACL.RemoveAccessRule($EveryoneRule)
# Set ACL on file again
Set-Acl $FilePath -AclObject $FileACL
To remove groups or users ACE without disabling inheritance, use CACLS folder /E /R group/user. I know that CACLS is deprecated but I have not found any equivalent when using iCacls or SETACL.
Actually you don't have to delete inheritance.
It is possible to just remove this one little mistake. Had the same error and it was successful on a Windows 2016 Fileserver.
I modified the Script from Mathias R. Jessen a bit. If you want to do this just to one Folder, replace "$folders = Get-Childitem" with "$filepath = Get-Item" and only use the commands inside the foreach loop.
Open Powershell as Admin
$folders = Get-ChildItem "C:\Path\To\Folder" | where {$_.psiscontainer -eq $true}
foreach ($FilePath in $folders)
{
$FileACL = Get-Acl $FilePath.FullName
$EveryoneRule = $FileACL.GetAccessRules($true,$true,[System.Security.Principal.NTAccount]) | Where-Object {$_.AccessControlType -eq "Deny"}
$FileACL.RemoveAccessRule($EveryoneRule)
Set-Acl $FilePath.FullName -AclObject $FileACL
}
Related
How (which command) can I use to grant permissions (full_control) to a user (service_account) on a folder using PowerShell?
Thank you!
I was trying to use icacls in my PowerShell but it's not working.
There are several ways to do this. If you don't want to install a module as James suggests above then:
# Get current access permissions from folder and store in object
$Access = Get-Acl -Path $FolderPath
# Create new object with required new permissions
$NewRule = New-Object System.Security.AccessControl.FileSystemAccessRule("MyDomain\MyUserOrGroup","FullControl","ContainerInherit,ObjectInherit","None","Allow")
# Add new rule to our copy of the current rules
$Access.AddAccessRule($NewRule)
# Apply our new rule object to destination folder
Set-Acl -Path $FolderPath -AclObject $Access -ErrorAction Stop
As James mentions though, using ACLs in Powershell without a module, whilst powerful, is also a pain. I only do it when I'm sharing scripts (so that there isn't a dependency on the module).
I would recommend using the NTFSSecurity Powershell module for setting the permissions as it's much easier to use (and understand) than acls!
To add permissions for a user is just one command.
I've shown two examples for both network paths/domain account and local folder/local user. They can be mixed in any way you can set via the GUI.
Add-NTFSAccess -Path "\\sdk\data\SHAREDIR\$NAME" -Account "Domain\K_NV_TEST_R" -AccessRights FullControl
Add-NTFSAccess -Path "C:\folder\subfolder" -Account "LocalComputerName\LocalUserName" -AccessRights FullControl
So I've got the next path: C:\folder1\folder2\fileName. Looking in the security tab on the C:\folder1 there is Alice username with full permissions. But going to the C:\folder1\folder2\fileName Alice isn't there yet. How can I insert with powershell v2 Alice member recursively in C:\folder1 so that all the files under root C:\folder1 will also have the same Alice username set with full permissions.
I've tried:
$acl = Get-Acl C:\folder1
$permission = "domain\Alice","FullControl","Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
$acl.SetAccessRule($accessRule)
$acl | Set-Acl C:\folder1
But it doesn't seem to apply for the C:\folder1\folder1\fileName. Guess I'm trying to apply permissions for Alice, which doesn't exist yet in the last fileName item.
As you can see in the FileSystemAccessRule documentation, the class has a property for inheritance.
You have to add the property to your $permission
$permission = "domain\Alice",
"FullControl",
[System.Security.AccessControl.InheritanceFlags]"ContainerInherit",
[system.security.accesscontrol.PropagationFlags]"None",
"Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
You could also recursively add the permissions by getting all child items with the Get-ChildItems cmdlet and piping them to the Set-Acl cmdlet like they have done in an examle in the documentation on microsoft site here: Set-Acl. Look at "Example 3: Apply a security descriptor to multiple files" or read below (copied from the page):
PS C:\> $NewAcl = Get-Acl File0.txt
PS C:\> Get-ChildItem -Path "C:\temp" -Recurse -Include "*.txt" -Force | Set-Acl - AclObject $NewAcl
These commands apply the security descriptors in the File0.txt file to all text files in the C:\Temp directory and all of its subdirectories.
The first command gets the security descriptor of the File0.txt file in the current directory and uses the assignment operator (=) to store it in the $NewACL variable.
The first command in the pipeline uses the Get-ChildItem cmdlet to get all of the text files in the C:\Temp directory. The Recurse parameter extends the command to all subdirectories of C:\temp. The Include parameter limits the files retrieved to those with the ".txt" file name extension. The Force parameter gets hidden files, which would otherwise be excluded. (You cannot use "c:\temp*.txt", because the -Recurse parameter works on directories, not on files.)
The pipeline operator (|) sends the objects representing the retrieved files to the Set-Acl cmdlet, which applies the security descriptor in the AclObject parameter to all of the files in the pipeline.
In practice, it is best to use the Whatif parameter with all Set-Acl commands that can affect more than one item. In this case, the second command in the pipeline would be "Set-Acl -AclObject $NewAcl -WhatIf". This command lists the files that would be affected by the command. After reviewing the result, you can run the command again without the Whatif parameter.
This is an example using ".txt" files but can be modified to apply to directories as well.
I am writing a script which would delete a specific user if the account is older than 7 days.
But when the user is deleted the NTFS permissions on my file server remain.
How can I delete all the permission for a specific user with PowerShell?
You should never grant permissions to individual users (with the exception of home directories and user profiles). As you can see for yourself it's a mess to clean up. Always create groups representing the particular functions/roles that require access, and grant permissions to those groups.
You can clean up the permissions via icacls:
icacls C:\root\folder /remove DOMAIN\user /t /c
Note, however, that you MUST do this before deleting the account, because for some reason icacls can't clean up SIDs of deleted accounts.
If you have already deleted the account you can try to fix permissions with Get-Acl and Set-Acl:
Get-ChildItem C:\root\folder -Recurse -Force | ForEach-Object {
$acl = Get-Acl -LiteralPath $_.FullName
$ace = $acl.Access | Where-Object { $_.IdentityReference -like 'S-1-5-*' }
$acl.RemoveAccessRule($ace) | Out-Null
Set-Acl -LiteralPath $_.FullName -AclObject $acl
}
Note that you may need to adjust the condition for selecting the ACE to remove from the file or folder's ACL.
Note also, that the above will fail for files/folders where the owner isn't either the user running the code or one of his groups. In a situation like that you can use tools like subinacl or SetACL as a last resort, as described in the answers to this question on ServerFault.
Trying to use powershell to reset permissions on files/folders copied over from a Linux machine.
Structure looks similar to this
E:\Parent Folder - No inheritance - Group based permissions
|
|
Folder01 - No inheritance
|
|
Subfolders and file - Group based permissions, inheritance
Folder02 - No inheritance
|
|
Subfolders and file - Group based permissions, inheritance
Folder03 - No inheritance
|
|
Subfolders and file - Group based permissions, inheritance
Folder04 - No inheritance
|
|
User Folder - User based permissions, No Inheritance
|
|
Inheritance
The script currently first runs the takeown command, followed by the icacls.
I then loop through the first level of folders to disable the inheritance.
Then the permissions are applied to the folders.
Here is a sample of what I have. It just repeats itself for each specific permission I want to set.
Get-ChildItem -Path "$solidPath" -ErrorAction SilentlyContinue | ForEach-Object {
$Item = $_.FullName
If ( "$Item" -eq "E:\ParentFolder\Folder04" -or "$Item" -eq "E:\ParentFolder\Folder03" )
{
Write-Host "Do Not Touch" -ForegroundColor DarkRed
}
Else
{
$colRightsAdmin = [System.Security.AccessControl.FileSystemRights]"FullControl"
$InheritanceFlagAdmin = [System.Security.AccessControl.InheritanceFlags]::ContainerInHerit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInHerit
$PropagationFlagAdmin = [System.Security.AccessControl.PropagationFlags]::None
$objTypeAdmin = [System.Security.AccessControl.AccessControlType]::Allow
$objUserAdmin = New-Object System.Security.Principal.NTAccount("BUILTIN\Administrators")
$objACEAdmin = New-Object System.Security.AccessControl.FileSystemAccessRule($objUserAdmin, $colRightsAdmin, $objTypeAdmin)
$objACLAdmin = Get-ACL "$Item"
$objACLAdmin.AddAccessRule($objACEAdmin)
Set-ACL "$Item" $objACLAdmin
I am using takeown + icacls to try and reset all the permissions. This initially worked well because the inheritance flags get reset as well.
I then use the method described in the link to set the appropriate permissions and inheritance on my folders and let the inheritance do the rest - Powershell & .net
The script worked on my test directory structure. But after coping the folders and files over I am getting a permission denied message when the icacls command runs (the takeown command runs without issue). The rest of the script then fails.
I know that I can use the RemoveAccessRule($objACE) to remove permissions from objects, but I haven't been able to figure out how to do it for all the user permissions that are defined.
I would like to start the folders and files off with a clean slate, and then apply permissions. All the examples I have found only show how to remove permissions for a specific user.
Where am I going wrong with the initial permission cleanup?
I ended up going with a bit of messy solution.
After I had a synced copy of the data from the Linux server I used robocopy to "move" all the data from one folder to another. This completely reset all the permissions on all the files.
After having done that I learned a little bit more about setting permissions and realized that I had been making a mistake all along.
I was aimlessly using this object to remove permissions
$acl.RemoveAccessRule($ace) | Out-Null
This was actually removing all privilege on the file before I had a chance to set any other permissions. So I was removing my ability to adjust permissions.
Once I realized this I used a combination of the properties IdentityReference and IsInherited to selectively target which permissions I was going to remove.
The script is big and ugly, but seems to work.
Thank you very much in advance for helping.
So I have hundreds of files and folders from which I'd like to remove the user: C850-108.
I can do this using Windows interface, but it'd take me days to do it in every file.
The reason I'd like to do this is because Cobian Backup tool can't have access to this files (Permission denied) and I think that user is the problem.
So I have Cygwin (bash) an PowerShell to help me in this tedious task.
I attach 3 screenshots:
Windows Security tab
PowerShell output of the command get-acl | format-list
Cygwin output of getfacl
I'm more experienced with bash, so I tried adding an user like this:
setfacl.exe -m u:rafaelgp:rwx myfile
Which apparently did nothing, but when I check with PowerShell, I saw that it actually worked and added a new user (rafaelgp) with the specified permissions. You can see this in the screenshots. So after this I lost some trust in Cygwin.
I've also tried deleting the user like this:
setfacl.exe -d u:C850-108 myfile
But I get the following message:
setfacl: illegal acl entries
So what can I do? As I said, I'm happy trying anything using bash or PowerShell.
Cheers!
UPDATE:
Screenshot of Musaab Al-Okaidi solution. There seems to be a problem with the '$file' parameter
The simplest way would arguably be icacls:
icacls file /remove C850-180
You can't remove permissions that were inherited from the parent folder with this, though. I suspect that this is the reason why setfacl failed. Unfortunately the inheritance information is suppressed when you pipe the output of Get-Acl into Format-List. Try this instead:
Get-Acl file | % { $_.Access } | ? { $_.IdentityReference -match 'C850-180' }
The IsInherited property will show you whether or not the ACL is inherited. If the ACL is inherited, you have to disable inheritance first before you can remove an ACL:
icacls file /inheritance:d
icacls is available since Windows Server 2003 SP2.
Update:
You can apply this recursively to a folder tree by adding the option /t:
icacls C:\some\folder\* /t /inheritance:d
icacls C:\some\folder\* /t /remove C850-180
Be advised, though, that it's not a good idea to recursively disable inheritance as it will make managing permissions a nightmare. Depending on your folder structure it might be better to simply remove inheritance and that particular ACE from the parent folder:
icacls C:\some\folder /inheritance:d
icacls C:\some\folder /remove C850-180
The subfolders and files will automatically inherit their parent folder's changed permissions. If necessary you can enforce that by resetting permissions on subfolders and files:
icacls C:\some\folder\* /reset /t /c
Add the following function to your shell, simply copy and paste, then you will have Remove-UserAccess as a usable Cmdlet
Function Remove-UserAccess()
{
Param
(
[Parameter(Mandatory=$true)][String]$Path,
[Parameter(Mandatory=$true)][String]$User
)
$Files = New-Object System.Collections.ArrayList
$Files.Add($Path) | Out-Null
#Add all files and folders to an array
$PathSubtree = Get-ChildItem -Path $Path -Recurse
Foreach ( $File in $PathSubtree )
{
$Files.Add($File.FullName) | Out-Null
}
# Remove access of the $User from each file in the array
Foreach ( $File in $Files )
{
$AccessRule = Get-Acl $File | % { $_.Access } | ? { $_.IdentityReference -eq $User}
IF ( $AccessRule -eq $null )
{
Write-Host "$User does not have access to $File" -ForegroundColor Yellow
}
ELSE
{
$ACL = Get-Acl $File
$ACL.RemoveAccessRule($AccessRule) | out-Null
Set-Acl -Path $File -AclObject $ACL -ErrorAction Stop
Write-Host "Permissions for $user have been removed from the following path: $File" -ForegroundColor Green
}
}
}
Execute the command as follows:
Remove-UserAccess -Path C:\temp -User RAFALAPTOP\C850-108
This will remove the access for the user from C:\temp and all sub-files and folders.