Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a folder is given access

I m new to PS scripting. Just started to write a script to find if a folder is permissionned properly for a user. The folder name and the AD account name is same. Say if the folder name is XX11223, then the user XX11223 should have access to that particular folder. The folders which are not properly permissionned should be printed to file. Someone pls help on this.

$Paths = Get-Content "Path.txt"

#To get the subfolders for which the permissions has to be checked

$Folder = foreach ($Path in $Paths) {
    $Path = $Path | Select-Object -Unique
    Write-Host $Path -ForegroundColor Green
    Get-ChildItem $Path | Where-Object { $_.Attributes -eq 'Directory' } | Select-Object FullName
}

#To get the ACLs for the list of folders from above

$ACLS = Get-Content $Folder

$Out = foreach ($ACL in $ACLS) { 
    Write-Host $ACL -ForegroundColor Cyan
    Get-Acl $ACL | Select-Object AccesstoString
}

I m stuck here and have not a faintest idea how to proceed. :(

like image 500
Balaji RR Avatar asked Sep 15 '25 17:09

Balaji RR


1 Answers

This all depends on what constitutes "proper permissions", but if you expect the user to have FullControl granted on his folder, you can do the following:

Retrieve the ACL of each folder:

$FolderAcl = Get-Acl $path

Construct an NTAccount object representing the corresponding folder

$Account   = New-Object System.Security.Principal.NTAccount "DOMAIN\user"

And then grab all explicit access rule entries from the ACL granting FullControl to the account in question:

$FullControl = $FolderAcl.GetAccessRules($true,$false,[System.Security.Principal.NTAccount]) | Where-Object {
    $_.FileSystemRights -eq "FullControl" -and 
    $_.AccessControlType -eq "Allow" -and 
    $_.IdentityReference -eq $Account
}

If $FullControl contains $null (ie. no access rules were found) print to file.

if(-not $FullControl){
    $path |Out-File C:\wrongPermissions.txt
}

If you want to find ACE's with Modify rights, including those where Modify is included in another rights (such as FullControl), you can perform a bitwise AND operation against the value of Modify, like so:

$ModifyValue = [System.Security.AccessControl.FileSystemRights]::Modify -as [int]
$ACEswithModify = $FolderAcl.Access |?{ ($_.FileSystemRights -band $ModifyValue) -eq $ModifyValue }
like image 77
Mathias R. Jessen Avatar answered Sep 18 '25 10:09

Mathias R. Jessen