====== Working with files and folders ======
===== View owner and current permissions =====
$myfile = ".\example.txt\"
(Get-Acl $myfile).Owner
(Get-Acl $myfile).Access | Format-Table IdentityReference, IsInherited, FileSystemRights
===== Set permissions for private folder =====
Only owner and //SYSTEM// has access to folder and subfolders. All inherited permissions removed:
$folder = ".\Documents\"
# Get current ACL
$acl = Get-Acl $folder
# Remove all explicit access rules
$acl.Access | ForEach-Object { $acl.RemoveAccessRule($_) }
# Disable inheritance and remove inherited permissions
$acl.SetAccessRuleProtection($true, $false)
# Get current user
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$acl.SetOwner([System.Security.Principal.NTAccount]$currentUser)
# Define new access rules
$ownerRule = New-Object System.Security.AccessControl.FileSystemAccessRule($currentUser, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$systemRule = New-Object System.Security.AccessControl.FileSystemAccessRule("SYSTEM", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
# Apply rules
$acl.SetAccessRule($ownerRule)
$acl.SetAccessRule($systemRule)
# Save updated ACL
Set-Acl -Path $folder -AclObject $acl
Write-Output "Permissions updated successfully for $folder. Owner: $currentUser"
===== Set permissions for normal folder =====
Owner, SYSTEM and Administrators has full access to folder and subfolders, Authenticated Users can read.
$folder = ".\normal\"
# Get current ACL
$acl = Get-Acl $folder
# Remove all explicit access rules
$acl.Access | ForEach-Object { $acl.RemoveAccessRule($_) }
# Disable inheritance and remove inherited permissions
$acl.SetAccessRuleProtection($true, $false)
# Get current user
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$acl.SetOwner([System.Security.Principal.NTAccount]$currentUser)
# Define new access rules
$ownerRule = New-Object System.Security.AccessControl.FileSystemAccessRule($currentUser, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$systemRule = New-Object System.Security.AccessControl.FileSystemAccessRule("SYSTEM", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$adminsRule = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$authUsersRule = New-Object System.Security.AccessControl.FileSystemAccessRule("Authenticated Users", "ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow")
# Apply rules
$acl.SetAccessRule($ownerRule)
$acl.SetAccessRule($systemRule)
$acl.SetAccessRule($adminsRule)
$acl.SetAccessRule($authUsersRule)
# Save updated ACL
Set-Acl -Path $folder -AclObject $acl
Write-Output "Permissions updated successfully for $folder. Owner: $currentUser"