简体   繁体   中英

List files by date in filename Powershell

I hope you are well.

I am new in Powershell and am trying to make a script that allow to list files 7 days old based on the date in the filename, then copy/move them to another directory.

File Structure: 2020_06_11_DB.txt YYYY_MM_dd

I have this piece of script set up but it only match the file with the reference date (DateRef) and not the least (old) of it:

$SourceDB = "C:\DB\"
$DestinationDB = "C:\Destination\DB\"
$DateRef = Get-Date ((Get-Date).AddDays(-7)) -Format yyyy_MM_dd

$Query = Get-ChildItem $SourceDB -Filter "*$DateRef*" |
ForEach-object {
    Copy-Item -Path $_.FullName -Destination $DestinationDB
}

I tried operators like -le and -lt but with no success. I would appreciate if you can help me.

Get-ChildItem $SourceDB -Filter '*.txt' | Where-Object {$_.BaseName -le "*$DateRef*"}

Thank you!

When comparing dates, you will want to work with DateTime objects. So the challenge is extracting date strings from file names and converting them to DateTime objects before doing the comparison.

$SourceDB = "C:\DB\"
$DestinationDB = "C:\Destination\DB\"
$DateRef = (Get-Date).AddDays(-7).Date

$Query = Get-ChildItem $SourceDB -File | Where {
    $_.BaseName -match '\d{4}_\d{2}_\d{2}' -and [datetime]::ParseExact(([regex]::Match($_.BaseName,'\d{4}_\d{2}_\d{2}').Value),'yyyy_MM_dd',$null) -le $DateRef } |
        Foreach-Object {
            Copy-Item -Path $_.FullName -Destination $DestinationDB
        } 
    

Explanation:

I don't want to discourage you from using -Filter because it is better than filtering inside of Where-Object . So you could filter partially that way first with something like -Filter '*_*_*' or wildcard your path -Path "$SourceDB*[0-9][0-9][0-9][0-9]_[0-9][0-9]_[0-9][0-9]*" .

Using -File parameter in Get-Childitem , returns only files.

(Get-Date).AddDays(-7).Date is 7 days before today at midnight.

$_.BaseName -match '\\d{4}_\\d{2}_\\d{2}' matches files with format ####_##_## .

[regex]::Match($_.BaseName,'\\d{4}_\\d{2}_\\d{2}').Value returns the matched string ####_##_## . [datetime]::ParseExact() converts the matched string (format 'yyyy_MM_dd') into a DateTime object.

-le is less than or equal to operator. So -le $DateRef returns dates older than or equal to $DateRef .

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