how to change the script to include the top folder?

Matt 101 Reputation points
2024-02-01T21:12:52.8266667+00:00

Hi all, found this script https://www.netwrix.com/how_to_export_folder_permissions.htmlbut only shows the subfolders under \fs1\Shared. If I need to include \fs1\Shared in the report also, can anyone help? Thank you!

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,628 questions
0 comments No comments
{count} votes

Accepted answer
  1. MotoX80 35,621 Reputation points
    2024-02-02T00:22:46.2533333+00:00

    This should work.

    $path = "c:\temp"                # The folder to analyze 
    $Report = @()
    $FolderPath = @($path)           # put top level folder first 
    $FolderPath += (Get-ChildItem -Directory -Path $path -Recurse -Force).FullName    # append subfolder names
    Foreach ($Folder in $FolderPath) {
        $Acl = Get-Acl -Path $Folder
        foreach ($Access in $acl.Access)
            {
                $Properties = [ordered]@{'FolderName' = $Folder;
                    'ADGroup or User' = $Access.IdentityReference;
                    'Permissions' = $Access.FileSystemRights;
                    'Inherited' = $Access.IsInherited}
                $Report += New-Object -TypeName PSObject -Property $Properties
            }
    }
    $Report | Export-Csv -path "C:\data\FolderPermissions.csv"
    

1 additional answer

Sort by: Most helpful
  1. Michael Taylor 57,216 Reputation points
    2024-02-01T22:49:19.3933333+00:00

    $FolderPath is the child directories under the given path. To include the path then just append it to your arrays you get back. The returned data is an array of file system objects. So you technically need a file system object for the root path as well. But since you don't seem to be using anything other than the filename here then you can simplify the code by just storing the filename.

    $sourcePath = '\\fs1\Shared'
    $files = dir -Directory -Path $sourcePath -Recurse -Force | Select-Object -ExpandProperty FullName
    $files += $sourcePath
    

    Then replace any references to $Folder.FullName with simply $folder as it now is just the full path.

    If you really want to keep using file system objects then the code would look like this.

    $files = dir ...
    $files += Get-Item $sourcePath
    

    Note that I'm assuming Get-Acl will work on the file share path. I've never tried it. If it doesn't then you'll need to get permissions a different way because a file share isn't a regular directory.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.