Powershell get-acl add user first and last name

Viewed 292

I have the following code that returns the ntfs permissions for a particular folder path.

$folders = Get-ChildItem -path d:\test" -recurse -force | ?{ $_.psiscontainer }

$output = @()

foreach($folder in $folders)
{
$rights = Get-Acl -path $folder.fullname

    foreach($right in $rights.Access)
    {
    $properties = [ordered]@{'foldername'=$folder.fullname;'username'=$right.identityreference;'permissions'=$right.filesystemrights}
    $output += New-Object -TypeName psobject -Property $properties
    }
}
$output | export-csv d:\output\folders_temp1.csv -NoTypeInformation -Encoding UTF8

Though it displays the username along with its respective permissions, I would like to display the first and last name associated to that user from the active directory.

Any ideas on how can that be achieved?

Thank you for your help.

1 Answers

Here is how I would approach this, using Group-Object so that you're not querying Active Directory for the same user over and over for each Access Control List.

It's important to note that @() and += is inefficient and that PSCustomObject can be casted which is also, more efficient than using an ordered hashtable and then converting it to a New-Object.

Another efficiency improvement, thanks to Mathias R. Jessen for his helpful feedback, is to implement a hash table ($map) to have a reference of the IdentityReference already queried, by doing so we would only be querying Active Directory only once per unique user.

# $_.PSIsContainer => Can be replaced with -Directory
$folders = Get-ChildItem -Path "D:\test" -Recurse -Force -Directory
$map = @{}

$output = foreach($folder in $folders)
{
    $rights = Get-Acl -Path $folder.fullname
    $groups = $rights.Access | Group-Object IdentityReference

    foreach($group in $groups)
    {
        if(-not $map.ContainsKey($group.Name))
        {
            $ref = Split-Path $group.Name -Leaf
            $user = Get-ADUser -LDAPFilter "(name=$ref)"
            $map[$group.Name] = $user
        }
        
        $aduser = $map[$group.Name]

        foreach($acl in $group.Group)
        {
            [pscustomobject]@{
                GivenName   = $aduser.GivenName
                Surname     = $aduser.Surname
                Foldername  = $folder.Fullname
                UserName    = $acl.IdentityReference
                Permissions = $acl.FilesystemRights
            }
        }
    }
}

$output | Export-Csv D:\output\folders_temp1.csv -NoTypeInformation -Encoding UTF8
Related