简体   繁体   中英

Powershell - Delete files older dan x days but exclude folders

I have found a script on the internet, I have edited a little bit but it's not working

Using Powershell WS 2008 R2 Standard

Script is :

$del480 = "I:\CISS\Upload"
Get-ChildItem $del480 -recurse *.* -force | 
    where {$_.lastwritetime -lt (get-date).adddays(-480)} | 
    Remove-Item -recurse

What I need is to add 4 folders to this script, that has to be excluded for deleting -480 days. this are the folders:

I:\CISS\Upload\_Atest
I:\CISS\Upload\_Reporting
I:\CISS\Upload\_Templates
I:\CISS\Upload\_Upload files

Can somebody help me please ? Please keep in mind that I am not a script writer, I can read a little bit. But if you add a text something like add -exclude ......., than I don't know where to put it.

There are multiple ways to handle this. You can do foreach-loops in your where to check against an array etc. The following is an alternative that only uses the pipeline.

Create an ignore-list of the paths, like this:

ignorelist.txt

I:\CISS\Upload\_Atest
I:\CISS\Upload\_Reporting
I:\CISS\Upload\_Templates
I:\CISS\Upload\_Upload files

Then try the following script

#I stored the date to avoid running it multiple times
$limit = (Get-Date).AddDays(-480)
$del480 = "I:\CISS\Upload"
#Specify path for ignore-list
$ignore = Get-Content "C:\Ignorelist.txt"

Get-ChildItem $del480 -Recurse | 
Where-Object {$_.LastWriteTime -lt $limit } |
Select-Object -ExpandProperty FullName |
Select-String -SimpleMatch -Pattern $ignore -NotMatch | 
Select-Object -ExpandProperty Line |
Remove-Item -Recurse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM