简体   繁体   中英

PowerShell: Delete Files Based on Date in Filename

I'm currently writing a PowerShell script to clear down files, based on a date in the file name. The file name includes a date in the format yyyyMMdd and a time in the format hhmmss .

For example, C:\temp includes:

ABCDEFG_123-1-20200724-140910.txt
HIJKLMN_456-2-20200322-120323.txt
OPQRSTU_789-3-20200514-136942.txt

I'm trying to delete files from the C:\temp directory, which include a file date which is ten days older than today (not based on the Windows modified date, or create date).

I'm able to get the filenames using the below, but I'm not sure how I'd pull the dates into the array, or compare the filename date to today's date.

$array = Get-ChildItem c:\temp | 
         Where-Object {!$_.PSIsContainer}

Any assistance would be greatly appreciated!

You need to get the files, filtered on the extension (*.txt) and add a Where-Object clause behind that to test if their filename includes something that might be a date-time in the format you describe.

Then check if this date is parsable to a true datetime object and if so, compare it to the current date minus 10 days. (midnight, forget the time part)

Because the third exampe does not hold a valid time part, and the time is really not important to test if the file is older than 10 days, we ignore the time in the comparison.

$refDate = (Get-Date).AddDays(-10).Date  # files must be older than 10 days ago

# get a list of FileInfo objects and filter only those that have what 
# seems to be a date in their name in format 'yyyyMMdd-HHmmss'
Get-ChildItem -Path 'C:\temp' -Filter '*.txt' -File | 
    Where-Object { $_.BaseName -match '(\d{8})-\d{6}$'} | 
    ForEach-Object {
        # capture the file's FullName property, because if this errors out
        # you will enter the catch block. In there, the `$_` automatic variable
        # contains the exception object, no longer the FileInfo object.
        $file = $_.FullName
        try {
            $date = [datetime]::ParseExact($Matches[1], 'yyyyMMdd', $null)
            if ($date -lt $refdate) { 
                $_ | Remove-Item -WhatIf
            }
        }
        catch {
            Write-Warning "File $file contains an invalid date"
        }
    }

Remove the -WhatIf switch if you find the info written to console is correct to actually remove the files.

If you are using a PowerShell version below 3.0, you cannot use the -File switch. Instead then use: $txtFiles = Get-ChildItem -Path 'C:\temp' -Filter '*.txt' | Where-Object {.$_.PSIsContainer -and $_.BaseName -match '(\d{8})-\d{6}$' } $txtFiles = Get-ChildItem -Path 'C:\temp' -Filter '*.txt' | Where-Object {.$_.PSIsContainer -and $_.BaseName -match '(\d{8})-\d{6}$' }

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