【问题标题】:Delete directory recursive fails for filtered-out directory?筛选出的目录删除目录递归失败?
【发布时间】:2016-01-19 11:11:22
【问题描述】:

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

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 : 找不到路径“C:\delete_old_pics\InputStream”,因为它确实存在
不存在。
在行:1 字符:151
+ ... 环 "\d{8}" | Remove-Item -Recurse -WhatIf -ErrorAction 停止
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : ObjectNotFound: (C:\delete_old_pics\InputStream:String) [Remove-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand

有人帮我解决这个问题吗?

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

M:\S6-仓库\20151016
M:\S6-仓库\20151017
M:\S6-仓库\20151018
M:\S6-仓库\20151019
M:\S6-仓库\20151020
M:\S6-仓库\20151021

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

还有 Ansgar 的建议

【问题讨论】:

  • Select-String "\d{8}" 的意义何在?它将返回匹配对象。您在寻找只有 8 位数字的文件夹吗?
  • 请看上面:)

标签: powershell directory get-childitem


【解决方案1】:

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 在他的评论中指出的那样,您可能需要锚定表达式 (^/$) 以避免匹配名称,例如 foo12345678 或 1234567890。

【讨论】:

  • 可能建议使用锚定匹配,因为这将匹配超过八个字符的文件夹
【解决方案2】:

您应该为您的查询尝试这个:

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

【讨论】:

  • 强制或禁止确认与这里的问题无关。
猜你喜欢
  • 1970-01-01
  • 2014-05-12
  • 2018-10-15
  • 2013-09-10
  • 2013-11-24
  • 2016-04-18
  • 1970-01-01
  • 2010-10-21
相关资源
最近更新 更多