Kolesar
Kolesar

Reputation: 1283

Delete directory recursive fails for filtered-out directory?

I wrote this command for remove specific directories:

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

But I'm getting this error:

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

Someone to help me with this?

Edit #1 (add directory output - search working properly):

M:\S6-Warehouse\20151016
M:\S6-Warehouse\20151017
M:\S6-Warehouse\20151018
M:\S6-Warehouse\20151019
M:\S6-Warehouse\20151020
M:\S6-Warehouse\20151021

Edit #2 Work with one more parameter: | Select -ExpandProperty Line before | Remove-Item -Force

and with Ansgar suggestion

Upvotes: 0

Views: 87

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200413

Select-String operates on the entire input object, not just the path, and it returns a MatchInfo object, not the matched path (or input object). I'd suggest extending the Where-Object filter instead of using 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

As @Matt pointed out in his comment you may want to anchor the expression (^/$) to avoid matching names like foo12345678 or 1234567890.

Upvotes: 2

Yogesh K
Yogesh K

Reputation: 1

You should try this for your query:

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

Upvotes: -3

Related Questions