繁体   English   中英

删除项不起作用,删除项不起作用

[英]Remove-Item doesn't work, Delete does

有没有人知道为什么Delete工作时Delete Remove-Item会失败?


在下面的脚本中,我得到了一个我想删除的文件列表。
使用Remove-Item我收到以下错误消息:

VERBOSE:在目标“\\\\ UncPath \\ Folder \\ test.rtf”上执行“删除文件”操作。 删除项目:无法删除项目\\\\ UncPath \\ Folder \\ test.rtf:拒绝访问该路径。

但是使用Delete会删除那些文件。

脚本

$files = gci \\UncPath\Folder| ?{ $_.LastWriteTime -le (Get-Date).addDays(-28) }

# This doesn't work
$files | Remove-Item -force -verbose

# But this does
$files | % { $_.Delete() }

powershell可能会对UNC路径产生奇怪的影响,我认为它可以使用当前提供程序预先设置UNC路径,您可以使用以下命令验证:

cd c:
test-path \\127.0.0.1\c$

返回TRUE

cd HKCU:
test-path \\127.0.0.1\c$

返回FALSE

在指定fullpath时我们告诉powershell使用文件系统提供程序 ,这解决了问题。 您还可以指定提供程序,如remove-item filesystem::\\\\uncpath\\folder

我终于可以重复这个和IMO它似乎是一个错误。 repro是拥有像C $这样的开放共享,但是为文件上的用户设置拒绝修改权限。 当我这样做时,我观察到:

PS> gci '\\Keith-PC\C$\Users\Keith\foo.txt' | ri -for
ri : Cannot remove item \\Keith-PC\C$\Users\Keith\foo.txt: Access to the path is denied.
At line:1 char:43
+ gci '\\Keith-PC\C$\Users\Keith\foo.txt' | ri -for
+                                           ~~~~~~~
    + CategoryInfo          : InvalidArgument: (\\Keith-PC\C$\Users\Keith\foo.txt:FileInfo) [Remove-Item], ArgumentExc
   eption
    + FullyQualifiedErrorId : RemoveFileSystemItemArgumentError,Microsoft.PowerShell.Commands.RemoveItemCommand

PS> gci '\\Keith-PC\C$\Users\Keith\foo.txt' | %{$_.Delete()} # <== this works!

我还观察到删除-Force参数也会删除文件而不会出错。 拒绝权限仍然允许我从Windows资源管理器中删除该文件,这使我相信该文件应该删除。 那么使用-Force参数是什么呢? 当我深入研究ErrorRecord时,我看到了这个:

Message        : Access to the path is denied.
ParamName      :
Data           : {}
InnerException :
TargetSite     : Void set_Attributes(System.IO.FileAttributes)
StackTrace     :    at System.IO.FileSystemInfo.set_Attributes(FileAttributes value)
                    at Microsoft.PowerShell.Commands.FileSystemProvider.RemoveFileSystemItem(FileSystemInfo
                 fileSystemInfo, Boolean force)

似乎-Force参数试图设置(更可能重置 )属性,并且文件的权限不允许它,例如:

PS> gci '\\Keith-PC\C$\Users\Keith\foo.txt' | %{$_.Attributes = 'Normal'}
Exception setting "Attributes": "Access to the path is denied."
At line:1 char:45
+ gci '\\Keith-PC\C$\Users\Keith\foo.txt' | %{$_.Attributes = 'Normal'}
+                                             ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], SetValueInvocationException
    + FullyQualifiedErrorId : ExceptionWhenSetting

所以在我看来,PowerShell应该首先尝试,如果-Force不存在,如果失败,那么尝试重置属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM