Public/Get-NestedFolderPermission.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
Function Get-NestedFolderPermission
{
    <#
        .SYNOPSIS
            Finds the permissions of nested folders.
 
        .DESCRIPTION
            Finds the permissions of nested folders. This will search
            through all folders recursively and enumerate the permissions
            with output to console or CSV.
 
        .PARAMETER Export
            If this switch is enabled, output will be directed to a CSV file.
         
        .EXAMPLE
            Get-NestedFolderPermission
         
        .EXAMPLE
            Get-NestedFolderPermission -Export
    #>


    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$True,Position=0,HelpMessage="Enter the path to check nested folder permissions.")]
        [ValidateScript({Test-Path $_})]
        [String]
        $FolderPath,
        [Parameter(Mandatory=$False,Position=1,HelpMessage="If used this will export to file instead of console.")]
        [Switch]
        $Export
    )

    #Get a list of the paths
    Try 
    {
        $Folders = Get-ChildItem -Directory -Path $FolderPath -Recurse -Force
    }
    Catch 
    {
        Throw "An error retrieving the folders has occured. Please verify that you have access to the folder path being checked."
    }
    #Create an empty array to store data.
    $Output = @()

    #Loop through folders and obtain permisisons, store permissions in Output array

    ForEach ($Folder in $Folders)
    {
        Try
        {
            $Acl = Get-Acl -Path $Folder.FullName
            ForEach ($AclAccess in $Acl.Access)
            {
                Try
                {
                    $Properties = [Ordered]@{'Folder Name'=$Folder.FullName;'Group/User'=$Access.IdentityReference;'Permissions'=$Access.FileSystemRights;'Inherited'=$Access.IsInherited}
                    $Output += New-Object -TypeName PSObject -Property $Properties   
                }
                Catch
                {
                    Write-Error "Could not add ACL to Output variable for $($Folder.FullName)"
                }
            }
        }
        Catch
        {
            Write-Error "Could not obtain ACL for folder $($Folder.Fullname)"
        }
    }

    #Write Output to console or CSV

    If($Export)
    {
        $Output | Export-CSV NestedFolderPermissions.csv -NoTypeInformation
        Write-Output "NestedFolderPermissions.csv exported to current directory"
    }
    
    Else 
    {
        $Output | Out-GridView
    }
}