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

Lie*_*ers 3 windows powershell

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


在下面的脚本中,我得到了一个我想删除的文件列表.
使用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() }
Run Code Online (Sandbox Code Playgroud)

Loï*_*HEL 8

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

cd c:
test-path \\127.0.0.1\c$
Run Code Online (Sandbox Code Playgroud)

返回TRUE

cd HKCU:
test-path \\127.0.0.1\c$
Run Code Online (Sandbox Code Playgroud)

返回FALSE

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


Kei*_*ill 4

我终于可以重现这个,在我看来,这似乎是一个错误。重现是拥有像 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!
Run Code Online (Sandbox Code Playgroud)

我还观察到,删除-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)
Run Code Online (Sandbox Code Playgroud)

似乎该-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
Run Code Online (Sandbox Code Playgroud)

所以在我看来,PowerShell 应该首先尝试好像-Force不存在一样,如果失败,然后尝试重置属性。