0
votes

Delete all Files in C:\temp older than Current day(s)

$Path = "E:\Testing\Order\123456"

$CurrentDate = Get-Date

Get-ChildItem $Path | Where-Object { $_.LastWriteTime -lt $CurrentDate } | Remove-Item

I am trying to run this script but it is deleting every thing. It is not maintain current date files. Is there any modification please suggesting me sir.

2
Have you got any code so far? Either use filter/exclusion or on Remove-Item or Get-ChildItem in order to not process some files. - vonPryz

2 Answers

1
votes

Make sure you get the file extensions right if they have any.

Get-ChildItem -Path C:\folder1\data -Include * -Exclude text.1, folder1  -Recurse | foreach { $_.Delete()}

Edit to answer the comment:

So you want to delete all files and folders in C:\folder1 except of files text.1 and folder.1 in data, other and alpha? It means you cannot remove these 3 folders too so they have to be excluded.

Get-ChildItem -Path C:\folder1\ -Include * -Exclude text.1, folder.1, alpha, data, other  -Recurse | foreach { $_.FullName}
0
votes

try this (and dont stay into your dir when you try) :

Get-ChildItem "C:\folder1\data\*" -Recurse | where Name -notin ('text.1', 'folder.1') | Remove-Item -Force -Recurse