In the world of system administration, managing permissions is a crucial task. Ensuring that the right users have the right access to the right resources is fundamental to maintaining the security and integrity of a system. This is where our PowerShell script comes into play. This script is designed to fetch permissions on the folders of a specified directory and export them into a CSV file.

Purpose of the Script

The primary purpose of this script is to provide an automated and efficient way to fetch and analyze folder permissions. It can be particularly useful in large systems where manually checking permissions can be time-consuming and error-prone.

The script allows for both recursive and non-recursive searches. A recursive search means that the script will check the specified directory and its subdirectories up to a certain depth, which can be defined by the user. A non-recursive search, on the other hand, will only check the specified directory itself.

How to Use the Script

Using the script is straightforward. Here are the steps:

  1. Create a new file in Notepad
  2. Copy the below script
  3. Save the script with the “.ps1” extension
    • For example: “Folder_permissions_analysis.ps1”
  4. Run the script in PowerShell by right-clicking it and selecting “Run with PowerShell”
  5. When prompted, provide the full path of the directory you want to check.
    • Enter the directory name as-is, quotes are not required even if the path contains spaces
  6. Next, you’ll be asked whether you want to enable recursive search. If you choose “Yes”, the script will extract files and permissions for the selected directory and its sub-directories. If you choose “No”, the script will get a list of all files and their permissions in the specified directory.
  7. If you chose to enable recursive search, you’ll be asked to specify the depth of recursion. For example, a depth of 0 will return only the immediate subdirectories of the chosen directory, while a depth of 999 will return all subdirectories.
  8. The script will then fetch the permissions of all folders up to the specified depth and export them into a CSV file. The CSV file will be named with the name of the folder, the date, and the time at which the analysis ended, and it will be saved in the location from where the script was launched.
    • ex: Scripts_folder_16-05-2024-21.41.36.csv

Do note that the date is in the following format: “dd/MM/yyyy/HH.mm.ss
This can be changed by rearranging the existing sections. “/” “.” and “:” can be used between them. The table below was taken from Microsoft’s documentation for the Get-Date PowerShell Cmdlet.

ddDay of the month – 2 digits
ddddDay of the week – full name
MMMonth number
yyyyYear in 4-digit format
HH:mmTime in 24-hour format – no seconds
<#
  .Synopsis
     Fetch permissions on the folders of a specified directory
  .DESCRIPTION
     It is possible to search recursively or non-recursively. The data will then be exported 
     into a CSV file in the current directory which can then be opened and sorted in Excel by going to "Data => from a text/CSV file" or using a similar approach for Google Sheets

     Recursive search allows you to search to a certain depth.
  .NOTES
     The script creates a file at the location from where it was launched and names it with the name of the folder, the date and time at which the analysis ended.
  #>

# Prompt the user to enter the full path of the directory to check
$Directory = Read-Host 'Provide the full path of the directory'

# Create a dialog box to ask the user if they want to enable recursive search
$Title = 'Recursive Search'
$message = 'Enable recursive search? Choose "Yes" to extract files and permissions for the selected directory and its sub-directories. Choose "No" to get a list of all files and their permissions in this directory.'
$Yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", 'Enable search in all directories and subdirectories'
$No = New-Object System.Management.Automation.Host.ChoiceDescription "&No", 'Do not perform search in subdirectories'
$Cancel = New-Object System.Management.Automation.Host.ChoiceDescription "&Cancel", 'Cancel the operation?'
$options = [System.Management.Automation.Host.ChoiceDescription[]]($Yes, $No, $Cancel)

# Store the user's choice in the variable $ResultRecurse_or_not
$ResultRecurse_or_not = $host.ui.PromptForChoice($Title, $message, $options, 0) 

# Based on the user's choice, perform the appropriate action
if ($ResultRecurse_or_not -eq 0) {
    # If the user chose to enable recursive search, ask them to specify the depth of recursion
    [int]$RecursionLevels = Read-Host "To what depth should recursion be performed? ex: 0 = 1 = Chosen_Directory\Subdirectory0 / 1 = Chosen_Directory\Subdirectory0\Subdirectory1. (999 for unlimited)"
    # If the user entered 999 for unlimited depth, search all directories and subdirectories
    if ($RecursionLevels -eq 999) 
    { 
        $FolderPath = Get-ChildItem -Directory -Path $Directory -Recurse -Force 
    }
    # Otherwise, search directories up to the specified depth
    Else { 
        $FolderPath = Get-ChildItem -Directory -Path $Directory -Recurse -Depth $RecursionLevels -Force 
    }
}
# If the user chose not to enable recursive search, only search the specified directory
ElseIf ($ResultRecurse_or_not -eq 1) {$FolderPath = Get-ChildItem -Directory -Path $Directory -Force}
# If the user chose to cancel the operation, output a cancellation message and stop execution
ElseIf ($ResultRecurse_or_not -eq 2) {
        Write-Output 'The operation has been cancelled!' 
        pause
    break;}

# Create an empty array to store the permissions of all folders
$Output = @()
# For each folder in the specified directory and its subdirectories (up to the specified depth), get the Access Control List (ACL)
ForEach ($Folder in $FolderPath) {
    $Acl = Get-Acl -Path $Folder.FullName
    # For each access entry in the ACL, create a new object with properties such as 'Folder Name', 'Group/User', 'Permissions', and 'Inherited', and add this object to the $Output array
    ForEach ($Access in $Acl.Access) {
        $Properties = [ordered]@{'Folder Name'=$Folder.FullName;'Group/User'=$Access.IdentityReference;'Permissions'=$Access.FileSystemRights;'Inherited'=$Access.IsInherited}
        $Output += New-Object -TypeName PSObject -Property $Properties            
    }
}

# Get the current date and time
$Date = Get-Date -Format "dd/MM/yyyy/HH.mm.ss"
# Get the name of the last item in the path of the specified directory
$Folder = Split-Path $Directory -Leaf
# Create a filename using the name of the folder, the date, and the time
$FileName = $Folder + "_" + $Date + ".csv"
# Export the $Output array to a CSV file with the specified filename
$Output | Export-Csv -Path $FileName -Delimiter ';' -NoTypeInformation -Encoding UTF8

# Pause the script execution until the user presses a key
pause

Import and use the data in Excel

The data can be used directly, as-is, but depending on your use case, some of the lines might not be worth keeping. We might, for example, want to remove groups or users that have access to all folders.

Importing the Data

  1. Open Excel and create a new, empty file
  2. Go to the “Data” menu and select “From Text/CSV” in the top-left corner
  3. Select the file and click "import". The Text Import Wizard should appear.
  4. In the wizard, select the Semicolon delimiter, then click Load.
  1. Click Finish to complete the import process.

Your data should now be displayed correctly in Excel.

Analyzing the Data

With the data imported, you can now use Excel’s powerful data analysis features to examine the folder permissions. For instance, you might want to filter out default users. Here’s how you can do that:

  1. If your data is already inside an Excel table with filters at the top (small arrows on the right of each cell), skip to step 5. Otherwise continue
  1. To add filters to your table, select all non-empty header cells (first row)
  2. Click on the Data tab in the ribbon.
  3. Select Filter. This will add drop-down arrows to each column in your data.
  4. Go to the ‘Group/User’ column and click on the drop-down arrow.
  5. Uncheck the box for any default users you want to exclude from the view, such as “Builtin\Administrators”.
  6. Click OK.

The data will now be filtered to exclude the selected users, allowing you to focus on the permissions of other users. For example, removing the default SYSTEM and Administrators accounts allows us to focus on actual user rights.

Remember, Excel offers a wide range of tools for sorting, filtering, and visualizing data, so feel free to experiment with these features to get the insights you need from your folder permissions data. Happy analyzing!

Leave a Reply

Your email address will not be published. Required fields are marked *