使用 Powershell 脚本获取文件名中的日期大于某个特定日期的文件

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

我有一个特定的日期“2021/11/28”,我想要文件名大于 2021/11/28 的示例文件名(如下)中的文件列表。不记得文件名的创建时间了。

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

我期待

 "abc_20211129_efg.*"
 "opq_20211130_rst.*"

非常感谢您的帮助。

您不需要严格地将字符串解析为日期([datetime] 个实例):因为嵌入在文件名中的日期 strings 的格式为他们的 lexical 排序等同于 chronological 排序,你可以直接比较字符串表示:

# 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.*|$)' 通过捕获组 ((...)) 查找每个文件名中恰好 8 位的(最后)运行,反映在自动$Matches 索引为 1 ($Matches[1]) 的变量条目,如果找到的话。

  • '2021/11/28"' -replace '/' 从输入字符串中删除所有 / 个字符,使日期字符串的格式相同。为简洁起见,上面的解决方案在每个循环操作中执行此替换。实际上,您会在循环之前执行一次一次,并将结果分配给一个变量以在循环内使用。