PowerShell: 如何獲取和修改文件或文件夾的訪問權限


獲取文件或文件夾訪問權限

Get-Acl -Path <File or Folder Path> | Format-List

修改文件訪問權限

修改文件訪問權限需要用到Set-Acl命令,使用-Path參數指定要修改的文件路徑,使用-AclObject參數指定一個對象,該對象相當於一個ACL模板,此ACL模板指定了用戶訪問資源的權限設定。該對象的設定需要調用"System.Security.AccessControl.FileSystemAccessRule"類。

   1:  $account = "test01win2k8r2\test"
   2:  $FileSystemRights = "FullControl"
   3:  $objType = [System.Security.AccessControl.AccessControlType]::Allow
   4:   
   5:  $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ($account,$FileSystemRights,$objType)
   6:  $Folder = "W:\Test\test.txt"
   7:  $acl = Get-Acl $Folder
   8:  $acl.SetAccessRule($accessRule)
   9:   
  10:  Set-Acl -Path $Folder -AclObject $acl

還可以通過Get-Acl獲取一個文件的訪問權限,然后修改另一文件使其具有同樣的訪問權限:

Get-Acl "W:\Test\test01.txt" | Set-Acl -Path "W:\Test\test02.txt"

修改文件夾訪問權限

與修改文件訪問權限類似,同樣應用Set-Acl命令,只是在調用FileSystemAccessRule時可以多指定參數InheritanceFlags和PropagationFlags來指定訪問權限的設定是否被子文件或子文件夾繼承:

http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.inheritanceflags.aspx

http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.propagationflags.aspx

 

   1:  $account = "test01win2k8r2\test"
   2:  $FileSystemRights = "FullControl"
   3:  $InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]::ObjectInherit
   4:  $PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
   5:  $objType = [System.Security.AccessControl.AccessControlType]::Allow
   6:   
   7:  $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ($account,$FileSystemRights,$InheritanceFlag,$PropagationFlag,$objType)
   8:  $Folder = "W:\Test\"
   9:  $acl = Get-Acl $Folder
  10:  $acl.SetAccessRule($accessRule)
  11:   
  12:  Set-Acl -Path $Folder -AclObject $acl

參數InheritanceFlags和PropagationFlags的影響矩陣如下表

image

http://camillelemouellic.blog.com/files/2011/07/02-Inheritance.png

http://camillelemouellic.blog.com/2011/07/22/powershell-security-descriptors-inheritance-and-propagation-flag-possibilities/

 

Examples

PowerShell相關:

http://stackoverflow.com/questions/3282656/setting-inheritance-and-propagation-flags-with-set-acl-and-powershell

C#相關:

http://www.c-sharpcorner.com/uploadfile/babu_2082/adding-groups-user-names-and-permissions-for-a-directory-in-C-Sharp/

 

參考文獻:

About "Get-Acl":

http://technet.microsoft.com/en-us/library/hh849802.aspx

About "Set-Acl":

http://technet.microsoft.com/en-us/library/hh849810.aspx

About "FileSystemAccessRule" Class:

http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesystemaccessrule.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM