SRP
SRP

Reputation: 1153

How to skip a folder and its sub-folder and files from getting deleted using PowerShell?

I have a PS script which deletes the folders and files from a particular path older than 15 days. I want to exclude "_tasks" folder and its contents from getting deleted but the scripts deletes the files and folders inside it even when I have provided -Exclude property to exclude _tasks folder and its contents.

Below is the script I am using.

How can I exclude the _tasks folder and its sub-folders and files from getting deleted?

Get-ChildItem –Path "F:\Suraj\Garbage" -Recurse -Exclude "__tasks" | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-15))} | Remove-Item -Force -Recurse

Below images shows that the files on the left side were deleted inside the _tasks folders. I don't want them to be deleted. Any suggestion for same would be helpful.

enter image description here

Upvotes: 0

Views: 396

Answers (1)

Frenchy
Frenchy

Reputation: 16997

this piece of code selects all files except folder _task and its subfolders..

Get-ChildItem -Path 'F:\Suraj\Garbage' -Recurse  | 
Select-Object  LastWriteTime -ExpandProperty FullName |
Where-Object { ($_ -notlike 'F:\Suraj\Garbage\_tasks*') -and ($_.LastWriteTime -lt (Get-Date).AddDays(-15))} |
Remove-Item -Force -Recurse

or better like Theo's suggest:

Get-ChildItem -Path 'F:\Suraj\Garbage' -Recurse  | 
Where-Object { ($_.FullName -notlike 'F:\Suraj\Garbage\_tasks*') -and ($_.LastWriteTime -lt (Get-Date).AddDays(-15))} |
Remove-Item -Force -Recurse

Upvotes: 0

Related Questions