没有权限复制文件

时间:2017-12-04 20:33:52

标签: powershell

我有一个powershell脚本,可以复制一些文件供以后Python脚本使用。复制操作是:

ls $env:MINGW_32 -r -ea silentlycontinue -fo -inc "*.dll" | % { cp $_.fullname "build\lib.win32-2.7" }

没什么特别有趣或不寻常的。有趣(令人沮丧)的部分是后来发生的事情:

error: [Error 5] Access is denied: 'build\\bdist.win32\\4758ccaeay32.dll'
事实上,CPython在distutils中有逻辑,它在复制DLL之后显式重置文件权限以避免这个问题。我试图在powershell中复制这个但是没有成功:

$location = ".\build";
#Search recursivly through location defined;
get-childitem -r $location | foreach{
     $tempLocation = $_.FullName;
     #Get ACL for tempLocation;
     $acl = get-acl $tempLocation;
     #Get SID of explicit ACL;
     $acl.Access | where{
          $_.isinherited -like $false} | foreach{
          #Foreach SID purge the SID from the ACL;
          $acl.purgeaccessrules($_.IdentityReference); 
          #Reapply ACL to file or folder without SID;
          Set-Acl -AclObject $acl -path $tempLocation;
     }
}

是否有任何建议要重置或最好避免首先复制文件权限,以便Python脚本不会失败?

1 个答案:

答案 0 :(得分:0)

尝试稍微不同的方法。而不是重建每个文件的ACL,而是构建一个ACL并将其应用于所有文件。此外,我认为您拨打.PurgeAccessRules(<IdentityReference>)的电话应改为.RemoveAccessRule(<AccessRule>)

$location = ".\build"

#Get ACLs for first file in the folder
$ACL = GCI $location -File | Select -First 1 | Get-Acl
#Remove all non-inherited access rules, piped to Out-Null to avoid 'True' spam as it removes rules
$ACL.Access | ?{!$_.IsInherited} | %{$ACL.RemoveAccessRule($_) | Out-Null}

#Search recursivly through location defined;
GCI -r $location | Set-Acl -AclObject $ACL

使用的别名(截断结果):

PS C:\Users\TMTech> Get-Alias GCI,?
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           GCI -> Get-ChildItem
Alias           % -> ForEach-Object
Alias           ? -> Where-Object