简体   繁体   中英

Powershell to remove files from CSV older than x days

I am trying to read a CSV with a list of files including folder path and then delete them if they are older than x days.

I can do this is I list folders in the csv but cannot get it to work for just files.

CSV

FullName,,,,,,,,,,,,,
E:\$RECYCLE.BIN\S-1-5-21-352280589-691296097-1232828436-9414\$RCUCS3H.txt,,,,,,,,,,,,,
E:\$RECYCLE.BIN\S-1-5-21-352280589-691296097-1232828436-9414\$RWF5KKJ.txt,,,,,,,,,,,,,
E:\Account Lockout Files\Alockout.zip,,,,,,,,,,,,,
E:\Account Lockout Files\AlockoutXP.zip,,,,,,,,,,,,,

PowerShell contains.

$DatetoDelete = (Get-Date).AddDays(-3650)

Get-Content 'C:\delete\1.csv' | ForEach-Object { $_.Trim() } | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item -Force

When I use the script I did above it just deletes the files even if they are older, please can any one assist? thanks.

You are almost there with your code, but you are missing the actual check for the last write time, if you use Get-Item to get the properties of the file, you will then have the LastWriteTime property for you to use in your Where-Object

The below should do what you need with just one extra command and a pipe

Get-Content 'C:\delete\1.csv' | ForEach-Object { 
$_.Trim()
Get-Item -Path $_ |Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item -Force
}

Thanks for sharing an example of the input csv file. We now can be sure it actually is csv with headers and therefore, using Get-Content is the wrong cmdlet.

Try with Import-Csv instead:

$DatetoDelete = (Get-Date).AddDays(-3650).Date  # set to midnight

Import-Csv -Path 'C:\delete\1.csv' | ForEach-Object {
    $file = Get-Item -Path $_.FullName -ErrorAction SilentlyContinue
    if (($file) -and $file.LastWriteTime -lt $DatetoDelete) {
        $file | Remove-Item -Force
    }
}

For some files in the csv you may not have permissions to delete, like perhaps the ones inside the E:\\$RECYCLE.BIN\\S-1-5-21-352280589-691296097-1232828436-9414 ..

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