Reputation: 706
I am in the process of creating a powershell script that extracts the permissions associated with a directory and outputs the results to a CSV. This script currently works as intended however, now I want to have it exclude the 'NT AUTHORITY\SYSTEM' and 'BUILTIN\Administrators' account from the list. Can you please tell me how I can achieve this?
$FolderPath = dir -Directory -Path "C:\GMT\Common\" -Recurse -Force
$Report = @()
Foreach ($Folder in $FolderPath) {
$Acl = Get-Acl -Path $Folder.FullName
foreach ($Access in $acl.Access)
{
$Properties = [ordered]@{'FolderName'=$Folder.FullName;'AD Group or User'=$Access.IdentityReference;'Permissions'=$Access.FileSystemRights}
$Report += New-Object -TypeName PSObject -Property $Properties
}
}
$Report | Export-Csv -path "C:\Temp\server_permissions.csv"
Upvotes: 0
Views: 1519
Reputation: 8442
If you re-factor your code a little to use the pipeline, then you can filter with Where-Object
:
Get-ChildItem -Directory -Path "C:\GMT\Common\" -Recurse -Force |
ForEach-Object {
$folder = $_
(Get-Acl -Path $folder.FullName).Access |
Where-Object IdentityReference -notin "NT AUTHORITY\SYSTEM","BUILTIN\Administrators" |
ForEach-Object {
[PsCustomobject]@{
'FolderName' = $folder.FullName
'ADGroupOrUser'= $_.IdentityReference
'Permissions' = $_.FileSystemRights
}
}
} | Export-Csv -path "C:\Temp\server_permissions.csv" -NoTypeInformation
Even if you don't want to use this method, one thing I'd recommend is to avoid using spaces in property names such as 'AD Group or User' = $Access.IdentityReference
. While this works, it will just give you unnecessary headaches later.
Upvotes: 0
Reputation: 433
You could just use an if
-statement like so:
$FolderPath = dir -Directory -Path "C:\GMT\Common\" -Recurse -Force
$Report = @()
Foreach ($Folder in $FolderPath) {
$Acl = Get-Acl -Path $Folder.FullName
foreach ($Access in $acl.Access) {
if (!($Access.IdentityReference -eq "BUILTIN\Administrators") -and !($Access.IdentityReference -eq "NT AUTHORITY\SYSTEM")) {
$Properties = [ordered]@{
'FolderName' = $Folder.FullName
'AD Group or User' = $Access.IdentityReference
'Permissions' = $Access.FileSystemRights
}
$Report += New-Object -TypeName PSObject -Property $Properties
}
}
}
$Report | Export-Csv -path "C:\Temp\server_permissions.csv"
Upvotes: 2