从Powershell脚本中排除结果

时间:2018-12-04 14:19:54

标签: powershell

我正在创建一个Powershell脚本,该脚本提取与目录关联的权限并将结果输出到CSV。该脚本当前可以正常运行,但是,现在我要从列表中排除“ NT AUTHORITY \ SYSTEM”和“ BUILTIN \ Administrators”帐户。您能告诉我如何实现吗?

$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"

2 个答案:

答案 0 :(得分:2)

您可以像这样使用if语句:

$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"

答案 1 :(得分:0)

如果您稍微重构代码以使用管道,则可以使用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

即使您不想使用此方法,我也建议避免在属性名称中使用空格,例如'AD Group or User' = $Access.IdentityReference。虽然可以,但以后只会给您带来不必要的麻烦。