Skip to content

Instantly share code, notes, and snippets.

@pcrockett-pathway
Created August 25, 2021 13:12
Show Gist options
  • Save pcrockett-pathway/e17264f1b7205daa3886d3b4ec69b310 to your computer and use it in GitHub Desktop.
Save pcrockett-pathway/e17264f1b7205daa3886d3b4ec69b310 to your computer and use it in GitHub Desktop.
Set file or directory permissions easily with a PowerShell cmdlet
<#
.SYNOPSIS
Set file system permissions for a given path and user
.EXAMPLE
.\Set-Permissions.ps1 -Path C:\foo -User SomeUser -Rights FullControl
Allow SomeUser to have full control over C:\foo
.EXAMPLE
.\Set-Permissions.ps1 -Path C:\foo -User SomeUser -Rights Read
Give SomeUser read-only access to C:\foo
.EXAMPLE
.\Set-Permissions.ps1 -Path C:\foo -User SomeUser -Rights Write -Remove
Remove SomeUser's ability to write in C:\foo
.EXAMPLE
.\Set-Permissions.ps1 -Path C:\foo -User SomeUser -Rights FullControl -Remove
Completely remove all permissions for SomeUser
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
# The file or directory path you want to set permissions for.
[string[]]$Path,
[Parameter(Mandatory=$true)]
# Specify which user to add permissions for.
[string]$User,
[Parameter(Mandatory=$true)]
# Specify what rights the user should have.
[Security.AccessControl.FileSystemRights]$Rights,
[Parameter()]
# Specify whether the rights should be allowed or denied. Defaults to Allow.
[Security.AccessControl.AccessControlType]$Action = "Allow",
[Parameter()]
# Instead of adding permissions, remove them
[switch]$Remove
)
$ErrorActionPreference = "Stop"
Set-StrictMode -Version 5.0
# Most common rights you might want to use:
#
# FullControl
# Write
# Read
# Modify
#
# Less common, more granular rights you can use:
#
# ReadAndExecute
# ListDirectory
# ReadData
# WriteData
# CreateFiles
# CreateDirectories
# AppendData
# ReadExtendedAttributes
# WriteExtendedAttributes
# Traverse
# ExecuteFile
# DeleteSubdirectoriesAndFiles
# ReadAttributes
# WriteAttributes
# Delete
# ReadPermissions
# ChangePermissions
# TakeOwnership
# Synchronize
#
$propagateFlags = "None"
$inheritFlags = [Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit
function setPerms([string]$fullPath) {
# Thanks to this blog post for helping me figure this stuff out:
#
# https://petri.com/how-to-use-powershell-to-manage-folder-permissions
#
$acl = Get-Acl $fullPath
$rule = [Security.AccessControl.FileSystemAccessRule]::new(
$User,
$Rights,
$inheritFlags,
$propagateFlags,
$action
)
if ($Remove) {
Write-Verbose "Removing $Rights rights from $fullPath"
$acl.RemoveAccessRule($rule) | Out-Null
} else {
Write-Verbose "Applying $Rights rights to $fullPath"
$acl.SetAccessRule($rule)
}
$acl | Set-Acl $fullPath
}
$Path | ForEach-Object {
setPerms (Resolve-Path $_).ProviderPath
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment