对于过滤掉的目录,删除目录递归失败?

Delete directory recursive fails for filtered-out directory?

我写了这个命令来删除特定目录:

Get-ChildItem M:\ -recurse -Directory -Exclude images,record |
  Where-Object { $_.CreationTime -lt (Get-Date).AddDays(-90) } |
  Select-String "\d{8}" |
  Remove-Item -Recurse -WhatIf -ErrorAction Stop

但是我收到了这个错误:

Remove-Item : Cannot find path 'C:\delete_old_pics\InputStream' because it does
not exist.
At line:1 char:151
+ ... ring "\d{8}" | Remove-Item -Recurse -WhatIf -ErrorAction Stop
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\delete_old_pics\InputStream:String) [Remove-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand

有人可以帮助我吗?

编辑 #1(添加目录输出 - 搜索正常工作):

M:\S6-Warehouse151016
M:\S6-Warehouse151017
M:\S6-Warehouse151018
M:\S6-Warehouse151019
M:\S6-Warehouse151020
M:\S6-Warehouse151021

编辑#2 使用另一个参数: | Select -ExpandProperty Line之前 | Remove-Item -Force

和 Ansgar 的建议

Select-String 对整个输入对象进行操作,而不仅仅是路径,它 returns 是一个 MatchInfo 对象,而不是匹配的路径(或输入对象)。我建议扩展 Where-Object 过滤器而不是使用 Select-String:

Get-ChildItem M:\ -Recurse -Directory -Exclude images,record | Where-Object {
  $_.CreationTime -lt (Get-Date).AddDays(-90) -and
  $_.BaseName -match '^\d{8}$'
} | Remove-Item -Recurse -WhatIf -ErrorAction Stop

正如@Matt 在他的评论中指出的那样,您可能希望锚定表达式 (^/$) 以避免匹配 foo123456781234567890 等名称。

您应该尝试这样查询:

Get-ChildItem -Path your_absolute_path -Exclude '*.png' |
  Where-Object { $_. LastWriteTime -lt (Get-Date).AddDays(-90) } |
  Select-String "\d{8}" |
  Remove-Item -Recurse -Force -Confirm:$false