$sharePath = "E:\Test" # 共享文件夹路径
$users = "syinsh\han1", "syinsh\han2" # 需要设置权限的用户
$permissions = "ReadOnly" # 权限等级,可以调整为 "Modify", "Write", "ReadOnly","FullControl"
# Import Active Directory module (if needed)
Import-Module ActiveDirectory
# 权限映射:映射字符串权限到 FileSystemRights 枚举值
$permissionsMapping = @{
"FullControl" = [System.Security.AccessControl.FileSystemRights]::FullControl
"Modify" = [System.Security.AccessControl.FileSystemRights]::Modify
"Write" = [System.Security.AccessControl.FileSystemRights]::Write
"ReadOnly" = [System.Security.AccessControl.FileSystemRights]::ReadAndExecute
}
# Function to set folder permissions
function Set-FolderPermissions {
param (
[string]$folderPath,
[string[]]$usersOrGroups,
[string]$permissions
)
# Convert string permission to FileSystemRights enum
$fileSystemRights = $permissionsMapping[$permissions]
# Set inheritance and propagation flags
$inheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
$propagationFlags = [System.Security.AccessControl.PropagationFlags]"None"
$accessControlType = [System.Security.AccessControl.AccessControlType]::Allow
# Get the current ACL for the folder
$acl = Get-Acl -Path $folderPath
# Iterate over each user and add the appropriate access rule
foreach ($userOrGroup in $usersOrGroups) {
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule (
$userOrGroup,
$fileSystemRights,
$inheritanceFlags,
$propagationFlags,
$accessControlType
)
# Add the access rule to the ACL (dont overwrite existing rules)
$acl.AddAccessRule($accessRule)
}
# Apply the updated ACL to the folder
Set-Acl -Path $folderPath -AclObject $acl
}
# For users
Set-FolderPermissions -folderPath $sharePath -usersOrGroups $users -permissions $permissions
Write-Output "Folder permissions for users have been configured."