How to Set Folder Permissions Using PowerShell

Ensuring that the right individuals have the proper access to specific files and folders is paramount in IT. Managing permissions effectively safeguards sensitive data, aids in regulatory compliance, and enhances operational efficiency. One popular tool for handling such tasks is PowerShell, and today, we dive deep into a script that streamlines the process of modifying folder permissions. 

Background

In an ever-evolving digital landscape, IT professionals and Managed Service Providers (MSPs) constantly juggle multiple user permissions across various files and folders. The script provided is a godsend in such scenarios. It offers flexibility, allowing permissions to be assigned or blocked for multiple users across multiple paths. This means, whether you’re working with individual files or entire directories, this script has you covered.

The Script


#Requires -Version 5.1

<#
.SYNOPSIS
    Modify User Permissions for files and folder.
.DESCRIPTION
    Modify User Permissions for files and folder. You can assign or block multiple permissions to multiple users, and multiple files and folders.
.EXAMPLE
     -User "Test" -Path "C:Test" -Permissions FullControl
    Gives FullControl permissions to the user Test for just the folder C:Test
.EXAMPLE
     -User "Test1", "Test2" -Path "C:Test" -Permissions FullControl
    Gives FullControl permissions to the user Test1 and Test2 for just the folder C:Test
.EXAMPLE
     -User "Test1", "Test2" -Path "C:Test", "C:Temp" -Permissions FullControl
    Gives FullControl permissions to the user Test1 and Test2 for just the folders C:Test and C:Temp
.EXAMPLE
     -User "Test" -Path "C:TestDocument.docx" -Permissions FullControl
    Gives FullControl permissions to the user Test for just the file C:TestDocument.docx
.EXAMPLE
     -User "Test" -Path "C:TestDocument.docx" -Permissions ReadData, Modify
    Gives ReadData and Modify permissions to the user Test for just the file C:TestDocument.docx
.EXAMPLE
     -User "Test" -Path "C:TestDocument.docx" -Permissions FullControl -Block
    Blocks FullControl permissions from the user Test for just the file C:TestDocument.docx
.EXAMPLE
     -User "Test" -Path "C:Test" -Permissions FullControl -Recursive
    Gives FullControl permissions to the user Test for the folder C:Test and any folder or file under it will inherit FullControl
.EXAMPLE
    PS C:> .Modify-User-Permissions.ps1 -User "Test" -Path "C:Test" -Permissions FullControl -Recursive
    Gives FullControl permissions to the user Test for the folder C:Test and any folder or file under it will inherit FullControl
.INPUTS
    Inputs (User,Path,Permissions)
.OUTPUTS
    FileSecurity
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes:
    Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
.COMPONENT
    ManageUsers
#>

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [ValidateScript(
        {
            # Validate that the User(s) exist
            if ($(Get-LocalUser -Name $_)) { $true } else { $false }
        }
    )]
    [String[]]
    # The user name of the user you want to apply Permissions to a Path(s)
    $User,
    [Parameter(Mandatory = $true)]
    [ValidateScript({ Test-Path -Path $_ })]
    [String[]]
    # File path that you want to apply Permissions to
    $Path,
    [Parameter(Mandatory = $true)]
    # Permission to set the path(s) for the user(s)
    # This accepts the following:
    #  ListDirectory, ReadData, WriteData, CreateFiles, CreateDirectories, AppendData, ReadExtendedAttributes,
    #  WriteExtendedAttributes, Traverse, ExecuteFile, DeleteSubdirectoriesAndFiles, ReadAttributes,
    #  WriteAttributes, Write, Delete, ReadPermissions, Read, ReadAndExecute, Modify, ChangePermissions,
    #  TakeOwnership, Synchronize, FullControl
    [System.Security.AccessControl.FileSystemRights[]]
    $Permissions,
    # Block the specified Permissions for the specified $User
    [Switch]
    $Block,
    # Apply the Permissions down through a folder structure, i.e. inheritance
    [Switch]
    $Recursive
)

begin {
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        if ($p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator))
        { Write-Output $true }
        else
        { Write-Output $false }
    }
}

process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }
    $Acl = Get-Acl -Path $Path
    if ($true -in $Acl.AreAccessRulesProtected) {
        Write-Error "ACL rules are protected for one of the specified paths."
        exit 1
    }
    $script:HasError = $false
    $Path | ForEach-Object {
        $CurPath = Get-Item -Path $_
        $User | ForEach-Object {
            $NewAcl = Get-Acl -Path $CurPath
            # Set properties
            $identity = Get-LocalUser -Name $_
            $fileSystemRights = $Permissions
            $type = $(if ($Block) { [System.Security.AccessControl.AccessControlType]::Deny }else { [System.Security.AccessControl.AccessControlType]::Allow })
            $fileSystemRights | ForEach-Object {
                # Create new rule
                Write-Host "Creating $type $_ rule for user: $identity"
                # Check if Recursive was used and that the current path is a folder
                if ($CurPath.PSIsContainer -and $Recursive) {
                    $inheritanceFlags = 'ObjectInherit,ContainerInherit'
                    $NewAcl.SetAccessRuleProtection($false, $true)
                }
                else {
                    $inheritanceFlags = [System.Security.AccessControl.InheritanceFlags]::None
                }
                $propagationFlags = [System.Security.AccessControl.PropagationFlags]::None
                $fileSystemAccessRuleArgumentList = $identity, $_, $inheritanceFlags, $propagationFlags, $type
                $fileSystemAccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $fileSystemAccessRuleArgumentList

                # Apply new rule
                $NewAcl.SetAccessRule($fileSystemAccessRule)
                try {
                    Set-Acl -Path $CurPath -AclObject $NewAcl -Passthru
                }
                catch {
                    Write-Error $_
                    $script:HasError = $true
                }
            }
        }
    }
    if ($script:HasError) {
        exit 1
    }
}

end {}

 

Access 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown

At its core, the script operates with three mandatory parameters: User, Path, and Permissions.

  • User: Defines the target user for whom permissions are being set. This parameter undergoes validation to ensure the user exists.
  • Path: Indicates the file or directory whose permissions need to be modified. Its existence is validated.
  • Permissions: Enumerates the various types of permissions that can be set, ranging from FullControl to specific ones like ReadData.

The script also offers optional parameters:

  • Block: If invoked, denies the specified permissions.
  • Recursive: If specified, applies permissions down a folder structure, ensuring inheritance.

When executed, the script first checks if it’s running with administrative privileges. It then assesses each path for the specified user permissions, creating or modifying rules accordingly.

Potential Use Cases

Imagine an IT professional, Jane, overseeing a project for her organization. Jane has a folder with project files. As the project progresses, different departments need various levels of access to these files. Using the script, Jane can effortlessly ensure that the HR department can only read certain documents, while the project managers have full control over all the files. This efficient management ensures smooth project operations while maintaining security.

Comparisons

Traditional methods of setting folder permissions often involve navigating through intricate GUI interfaces or employing third-party software. While they offer visual feedback, they can be time-consuming and less efficient when dealing with bulk permissions. The PowerShell script offers a faster, more direct approach. It’s especially handy for IT pros familiar with the command line, enabling rapid, script-driven permission changes.

FAQs

  • What are the OS requirements for this script? 
    The script supports Windows 10 and Windows Server 2016 and later.
  • How can I ensure the recursive permissions are applied only to folders and not individual files? 
    The script automatically checks if the path is a container (folder) and only then applies recursive permissions.

Implications

Effective permissions management is critical for IT security. Setting overly permissive access can expose sensitive data, while restrictive permissions can hinder work processes. This script provides a fine balance, enabling precise permission control. However, misconfigurations can have unintended implications, so always double-check your settings.

Recommendations

  • Always run a test in a controlled environment before deploying the script widely.
  • Backup current permissions settings, offering a safety net in case of errors.
  • Regularly update and audit user permissions to maintain security and operational efficiency.

Final Thoughts

In the modern IT world, the challenge of managing folder and file permissions can’t be overstated. PowerShell scripts, such as the one we explored today, make the task more manageable and efficient. For those looking for integrated IT management solutions, NinjaOne offers robust tools and capabilities, further easing the complexities of permissions management. Whether you’re leaning on scripts or comprehensive platforms like NinjaOne, the goal remains the same: secure, efficient, and streamlined IT operations.

Add a Comment

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

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

Watch Demo×
×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).