简体   繁体   中英

Get the files whose date in the filename is greater than some specific date using Powershell script

I have a specific date "2021/11/28", i want the list of files from example filenames(below) whose file name is greater than 2021/11/28. remember not the creation time of the file names.

 "test_20211122_aba.*"
 "abc_20211129_efg.*"
 "hij_20211112_lmn.*" 
 "opq_20211130_rst.*"

I'm expecting to get

 "abc_20211129_efg.*"
 "opq_20211130_rst.*"

Really appreciate your help.

You don't strictly need to parse your strings into dates ( [datetime] instances): Because the date strings embedded in your file names are in a format where their lexical sorting is equivalent to chronological sorting, you can compare the string representations directly:

# Simulate output from a Get-ChildItem call.
$files = [System.IO.FileInfo[]] (
  "test_20211122_aba1.txt",
  "abc_20211129_efg2.txt",
  "hij_20211112_lmn3.txt",
  "hij_20211112_lmn4.txt",
  "opq_20211130_rst5.txt"
)

# Filter the array of files.
$resultFiles = 
  $files | Where-Object {
    $_.Name -match '(?:^|.*\D)(\d{8})(?:\D.*|$)' -and
      $Matches[1] -gt ('2021/11/28"' -replace '/')
   }

# Print the names of the filtered files.
$resultFiles.Name
  • $_.Name -match '(?:^|.*\D)(\d{8})(?:\D.*|$)' looks for (the last) run of exactly 8 digits in each file name via a capture group ( (...) ), reflected in the automatic $Matches variable's entry with index 1 ( $Matches[1] ) afterwards, if found.

  • '2021/11/28"' -replace '/' removes all / characters from the input string, to make the format of the date strings the same. For brevity, the solution above performs this replacement in each loop operation . In practice, you would perform it once , before the loop, and assign the result to a variable for use inside the loop.

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