【问题标题】:Get the files whose date in the filename is greater than some specific date using Powershell script使用 Powershell 脚本获取文件名中日期大于某个特定日期的文件
【发布时间】:2022-01-02 06:14:08
【问题描述】:

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

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

我期待得到

 "abc_20211129_efg.*"
 "opq_20211130_rst.*"

非常感谢您的帮助。

【问题讨论】:

  • 一开始他们都会有test_吗?
  • 嗯,到目前为止你尝试了什么?
  • 我已经编辑了文件名,因为它们都是独一无二的。我试过这段代码,但它不工作。 $_.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) -gt "2021_11_28" }

标签: powershell powershell-4.0


【解决方案1】:

您不需要将字符串解析为日期([datetime] 实例):因为嵌入在文件名中的日期 strings 的格式是它们的词法 em>排序相当于时序排序,可以直接比较字符串表示:

# 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 位数字,这反映在具有索引 1 ($Matches[1]) 的自动 $Matches 变量条目中之后,如果找到的话。

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

【讨论】:

  • 当然,我会的。不知怎的,我看不到我之前的评论。再次评论“太棒了!你的代码就像一个魅力。非常感谢”
  • 你能帮忙吗?我正在处理需要与今天的日期进行比较的其他脚本。像这样的东西..但我遇到了格式问题。 Where-Object {$_.Name -match '(?:^|.*\D)(\d{8})(?:\D.*|$)' -and $Matches[1] -eq (Get-Date).Date}
  • @Razz,将(Get-Date).Date 替换为(Get-Date).ToString('yyyyMMdd')。如果您需要进一步的帮助,请创建一个新问题帖。
猜你喜欢
  • 1970-01-01
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 2014-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多