Checking permissions on folders

I have a script that runs through and checks for folders with a given name, and if it finds them, it gives authenticated users full control of the directory. The other part of the task is what I am stuck on. I need to be able to check permissions on the folders to make sure that it has been applied and not keep applying it in a loop. I’ve run through various code trials for about a week, and while they work on my test machines, they don’t seem to work in production. This is my latest trial:

$Folders = Get-ChildItem ‘C:’ -Filter “<mask>” -Recurse -Force -Directory -ErrorAction SilentlyContinue
foreach ($Directory in $Folders) {
$Test = Get-Acl $Directory.FullName | Select-Object -Property Path -ExpandProperty Access |
Where-Object identityreference -EQ “NT AUTHORITY\Authenticated Users” |
Where-Object FileSystemRights -NE “FullControl” |
Where-Object FileSystemRights -GT 1
}
If (($Test.Length -ne $Folders.Length) -and ($Test.Length -gt 0)) { write “detected=true” }

The thought was that $Folders would have the array of directories that matched the mask, $Test would have the array of folders that do NOT have authenticated users full control, and if the two don’t match, then the task needs to run. The test for greater than 1 at the end is because I found that one of the access rights returned is always some negative number, so that would always give me a false positive. Insight would be appreciated, thanks.

I changed the location of FullName and got it to work…

$Folders = (Get-ChildItem C:\temp -recurse -directory).FullName
foreach ($Directory in $Folders) {
$Test = Get-Acl $Directory | Select-Object -Property Path -ExpandProperty Access |
Where-Object identityreference -EQ "NT AUTHORITY\Authenticated Users" |
Where-Object FileSystemRights -NE "FullControl" |
Where-Object FileSystemRights -GT 1
}
If (($Test.Length -ne $Folders.Length) -and ($Test.Length -gt 0)) { write "detected=true" }

Thanks for the reply. That change worked sometimes for me, but not all the time. I realized I needed to check for explicit rights vs inherited rights as well. I went back to the drawing board and did a few more web searches. I finally ended up with the below, which is a slight modification from the one found at https://community.spiceworks.com/topic/493582-list-file-permissions-that-are-not-inherited

$Test = Get-childitem ‘C:’ -Filter “<Mask>” -Recurse -Force -Directory -ErrorAction SilentlyContinue |
Get-Acl | % {
$path = $.Path
$
.Access | % {
New-Object PSObject -Property @{
Folder = $path.Replace(“Microsoft.PowerShell.Core\FileSystem::”,"")
Access = $.FileSystemRights
Control = $
.AccessControlType
User = $.IdentityReference
Inheritance = $
.IsInherited
}
}
} | Where-Object {-not $.Inheritance } |
Where-Object { $
.User -eq “NT AUTHORITY\Authenticated Users” } |
Where-Object { $_.Access -ne “FullControl” }

If ($Test -ne $null) { “detected=true” }