Link to home
Start Free TrialLog in
Avatar of bjennings
bjennings

asked on

Powershell Delete items older than question

Hi,
I have a powershell script that removes files inside a folder older than a certain number of days. It works on some files and not others and I cannot figure out why it won't delete certain files. Here is the script.
$OlderThan = (get-date).AddDays(-2) #Change number to whatever is necessary
$ParentFolder = "redacted" #Change to necessary Directory

get-childitem $ParentFolder -recurse | where {$_.lastwritetime -lt $olderthan} |% {Remove-Item $_.FullName -force -Recurse} 

Open in new window


So the wierd part is if I run the first part of the script...It does list all the files I expect to be deleted. But when I run the entire thing with the -WhatIf switch, it only will delete one of the files. Please see the below image   User generated image
ASKER CERTIFIED SOLUTION
Avatar of bjennings
bjennings

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of oBdA
oBdA

In case you're still interested in a proper solution: you can keep the folder names. All you have to do is use the argument -LiteralPath with Remove-Item. The -Path argument supports wildcards, including a character set inside square brackets.
You should use the -File argument for Get-ChildItem (because you do not want to filter folders by date), and accordingly remove the -Recurse argument for Remove-Item:
$OlderThan = (Get-Date).AddDays(-2) #Change number to whatever is necessary
$ParentFolder = "redacted" #Change to necessary Directory

Get-ChildItem -Path $ParentFolder -Recurse -File | Where-Object {$_.lastwritetime -lt $olderthan} | ForEach-Object {Remove-Item -LiteralPath $_.FullName -Force} 

Open in new window