文件夹权限设置:对象安全组

Steven · 2024-11-28 20:06 · 53 views · Windows · old id 195

# Define variables
$sharePath = "E:\Test"  # 共享文件夹路径
$groupName = "syinsh\Domain Users"  # 需要设置权限的群组
$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 group 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 groups
Set-FolderPermissions -folderPath $sharePath -usersOrGroups $groupName -permissions $permissions

Write-Output "Folder permissions for group have been configured."

← Back to home