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

posted @ 2013-04-27 14:19  ITGirl笑笑  阅读(8659)  评论(0编辑  收藏  举报