1

I want to delete 30 days old folder & all sub folder which name start "dba_20200312-0500311 - 123"

# $curDateTime = Get-Date -Format yyyyMMdd-HHmmss, folder save in this date format 

$mydays = (Get-Date).AddDays(30)
$path = "E:\share\New folder\"
Get-Childitem -path $path -recurse -force | Where-Object { !$_.LastWriteTime -lt $mydays} | Remove-Item -Recurse -Force -confirm:$false -Verbose

I was using this script but it not delete with the name of folder which is save in date wise.

Moshe Katz
  • 3,112
  • 5
  • 28
  • 43
  • your code shows you basing the decision on the `.LastWrtiteTime` of the files & dirs. your discussion seems to prefer to use the date embedded in the folder name. which do you actually want to use? – Lee_Dailey May 25 '20 at 04:41

1 Answers1

0

First of all, you are missing the "-" sign in the AddDays method for get-date.

To match the file name and the last write time, you will need to tweak your Where-Object conditions, try if this expression matches the files that you need to delete before passing this to Remove-Item:

Get-ChildItem -Path "E:\share\New folder\" -Recurse | Where-Object {$_.PSIsContainer -eq $true -and $_.Name -match "dba_20200312-0500311" -and $_.LastWriteTime -gt ((get-date).AddDays(-30))}
Gabriel Talavera
  • 1,377
  • 1
  • 11
  • 18