Remove special NTFS permission from folder - powershell

Below is the code I am currently using to remove the special NTFS permission from folder
$path = "F:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn"
$acl = get-acl $path
icacls $path /reset /t /c /l /q
icacls $path /inheritance:d
Set-Acl -Path $path -AclObject $acl
# Check the existing rights
$acl.Access | where IdentityReference -Like 'BUILTIN\Users'
# Get a list of the rules to remove
$rules = $acl.access | Where-Object {
!$_.IsInherited -and
$_.IdentityReference -like 'BUILTIN\Users' -and
$_.FileSystemRights -in 'CreateFiles, AppendData'
}
ForEach($rule in $rules) {
$acl.RemoveAccessRule($rule)
}
$acl.Access
Set-Acl -Path $path -AclObject $acl
This code is working fine and removing the special permission from the folder. But the problem is the folder is also having 2 SYSTEM permission. 1 applies to this folder and another applies to folder and subfolder.
The script is removing the first SYSTEM permission as well which is for this folder.
Please let me know what is issue here.
Addition: I just identified that once icacls $path /reset /t /c /l /q command is executing, it is removing the SYSTEM permission.

You have included !$_.IsInherited and the first System permission is not inherited from F:\ like the others. So it's included in the result and you remove it.

Related

Can't see parent directory when assigning subdirectory permissions

Sorry everyone, for bothering you. Currently I have a command line to enforce user permissions already working on the specified directory but I need your help on how to be able to see the higher level directory when the user accesses it. Because now, when the user accesses normally, he will not see a higher-level directory to access, he must access the available path, so it is very inconvenient. I just need to see the folders to access without editing or see another subfolder inside.
$acl = Get-Acl 'D:\TEST'
$path = "D:\TEST"
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("test.ktdv","write","ContainerInherit,ObjectInherit","None","Allow")
$acl.AddAccessRule($rule)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("test.ktnb","read","ContainerInherit,ObjectInherit","None","Allow")
$acl.AddAccessRule($rule)
Get-ChildItem -Path "$Path" -Recurse -Force |
Where-Object { ($_.Name -eq 'New Folder' -or $_.Name -eq 'B') } |
Set-Acl -Aclobject $acl -Verbose

Remove network drive permissions of a user in all subdirectories

I am trying to remove a user from all subdirectories in a network share.
I have tried the following command: ICACLS X:\ /remove:g username /T
The command runs without failure (although it takes 3.5 hours due to the size of the shard drive) but after I check the permissions, the user's permissions are not deleted from anywhere.
If I navigate to a specific folder where I know that the user has access and run the command there (for example ICACLS X:\subdirectory /remove:g username /T ), it works just fine.
The issue seems to occur only if I try to run it from the root X:\ in which case, no permissions are deleted.
Any ideas why this might be the case?
P.S. I have F access on the root on the account I'm running the command with
Should do it with icacls /T. Unless the user running the command cannot read some directories. But if inheritance is enabled on the folders you probably have Administrators everywhere.
A simple PS Script can do it. With some try / catch around $acl | Set-Acl this can be used as a dry-mode in a non-privileged session. With a privileged session this will effectively replace the ACL on the directory.
$path = "X:"
$username = "Domain\User"
Get-Item -Path $path -Directory -Recurse | %{
$acl = Get-Acl -Path $_.FullName
$aces = $acl.Access | Where-Object { -not $_.IsInherited -and $_.IdentityReference.Value -eq $username }
if ($aces -ne $null -and $aces.Count -gt 0) {
Write-Host "Found $($aces.Count) ACE granted for $username on $($_.FullName)"
foreach($ace in $aces) {
$acl.RemoveAccessRule($ace)
}
$acl | Set-Acl -Path $_.FullName
}
}

Powershell taking ownership of folder before set-acl

Can I take over ownership and then set-acl to a folder? I have a folders.txt file where I have the location of the folder.
For Example:
D:\Dept\CC\NorthRiver\16-17\StaffAdministration
Then I am creating a new year of the previous year folder structure and copying the rights and permissions of the previous years folders to the new folder years matching folder. I ran into an issue though because of ownership of the folder. If I am not the owner I can not duplicate the permissions of certain folders and I receive Set-ACL : The security identifier is not allowed to be the owner of this object. Is there any way around this?
I tried adding the line (to change the owner to me but that did not work either):
get-item $currentFolder.Replace("16-17", "15-16") | set-owner -Account 'VDB-TST1\Administrators'
Does anyone have any ideas of how I may accomplish this?
This is the full script I have:
Function Get-FileName{
[CmdletBinding()]
Param(
[String]$Filter = "|*.*",
[String]$InitialDirectory = "C:\")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $InitialDirectory
$OpenFileDialog.filter = $Filter
[void]$OpenFileDialog.ShowDialog()
$OpenFileDialog.filename
}
#Get and Set the ACL to the new years folder structure
foreach ($currentFolder in (GC (Get-FileName -InitialDirectory $env:USERPROFILE\Desktop -Filter "Text files (*.txt)|*.txt|All files (*.*)|*.*"))) {
md $currentFolder # Create Folder
get-item $currentFolder.Replace("16-17", "15-16") | set-owner -Account 'VDB-TST1\Administrators'
Get-ACL $currentFolder.Replace("16-17", "15-16") | Set-ACL $currentFolder
}
I think you are running into the same limitations of Set-ACL and Get-ACL described in this post. try changing
Get-ACL $currentFolder.Replace("16-17", "15-16") | Set-ACL $currentFolder
to
(Get-Item $currentFolder.Replace("16-17", "15-16")).GetAccessControl('Access') | Set-ACL $currentFolder
As an alternative you can use robocopy to copy the ntfs permissions from one directory and then apply them to another.
robocopy $currentFolder.Replace("16-17", "15-16") $currentfolder /copy:S /SECFIX
Hope this helps.
The Set-ACL cmdlet native to powershell is pretty terrible. I would suggest using the NTFS module that is available. I have tried playing with Set-ACL several times and it always wastes more of my time rather than actually being useful.

How can I set desktop.ini ACL to allow me to delete it?

I'm trying to delete some users from AD and also take out their home directories. However, we have a script that denies us Administrators rights to their desktop.ini's because that stops their folder name being resolved in Explorer. However, when I want to blow out their whole home directory, the fact that there desktop.ini is still there means the parent folder can't be deleted either. I thought the below script would give me rights but it hasn't. What am I missing guys?
If (Test-Path $homeDir) {
$user = $_.uname
Set-ItemProperty -Path "\\server\students\home\$user" -Name Attributes -Value "Normal"
$acl = Get-Acl "\\server\students\home\$user"
$acl.access | where-object {$_.AccessControlType -eq "Deny"} | Foreach-object { $acl.RemoveAccessRule($_) }
(Get-Item "\\server\students\home\$user").SetAccessControl($acl)
Get-ChildItem -Path "\\server\students\home\$user\*" -Recurse | Remove-Item -Force -Recurse
Remove-Item "\\server\students\home\$user" -Recurse
Write-host "$user's home directory deleted successfully"
}
It's external to PowerShell (runs within PS just fine though) but I would suggest using icalcs as it makes this much simpler...
icacls "\\server\students\home\$user" /grant administrators:F /t

How to remove an User from a file, using Cywin or Powershell

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.