对于已过滤的目录,删除目录递归失败了吗?

时间:2016-01-19 11:11:22

标签: powershell directory get-childitem

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

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-Warehouse\20151016
M:\S6-Warehouse\20151017
M:\S6-Warehouse\20151018
M:\S6-Warehouse\20151019
M:\S6-Warehouse\20151020
M:\S6-Warehouse\20151021

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

和Ansgar的建议

2 个答案:

答案 0 :(得分:2)

Select-String对整个输入对象进行操作,而不仅仅是路径,它返回一个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等名称。

答案 1 :(得分:-3)

您应该尝试以下查询:

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