Powershell - Delete files older dan x days but exclude folders

主宰稳场 提交于 2021-02-11 15:54:54

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/16608613/powershell-delete-files-older-dan-x-days-but-exclude-folders

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!