【问题标题】:How to fetch the file with the file naming convention in Powershell如何在 Powershell 中使用文件命名约定获取文件
【发布时间】:2022-01-11 19:16:46
【问题描述】:

我想使用 powershell 脚本从目录中的其他文件列表中获取具有以下文件命名约定的今天的文件。需要匹配今天的日期和文件名。

TransferAA_MGH_20211206070920_xlsx.XLSX
TransferBB_MGH_20211206071130_xlsx.XLSX

我在下面尝试过,但它不起作用。 Get-ChildItem -Path Testfolder\*.XLSX | Where-Object {$_.Name -match '(?:^|.*\D)(\d{8})(?:\D.*|$)' -and $Matches[1] -eq ((Get-Date).Date) 感谢您的帮助。

【问题讨论】:

    标签: powershell powershell-4.0


    【解决方案1】:

    这应该适合你:

    Get-ChildItem -Path Testfolder\*.XLSX | 
      Where-Object {$_.Name -cmatch 'Transfer[A-Z]{2}_MGH_[0-9]{14}_xlsx.XLSX' -and $Matches[1] -like (Get-Date -Format "yyyyMMdd").Date}
    

    分解regex 模式:

    • Transfer - 文字字符串
    • [A-Z]{2} - 两个大写字母
    • _MHM_ - 文字字符串
    • [0-9]{14} - 14 位数字
    • _xlsx.XLSX - 文字字符串

    (Get-Date -Format "yyyyMMdd").Date 语法用于将今天的日期正确格式化以进行比较。

    【讨论】:

    • 此代码正在获取与“Transfer[A-Z]{2}_MGH_[0-9]{14}_xlsx.XLSX”匹配的所有文件。但我只需要今天的文件。请提出建议。
    【解决方案2】:

    这对我有用,你可以试一试。举个例子:

    $today = [datetime]::Today
    
    @'
    TransferAA_MGH_20211206070920_xlsx.XLSX
    TransferBB_MGH_20211206071130_xlsx.XLSX
    TransferAA_MGH_20211205070920_xlsx.XLSX
    TransferBB_MGH_20211205071130_xlsx.XLSX
    TransferAA_MGH_20211204070920_xlsx.XLSX
    TransferBB_MGH_20211204071130_xlsx.XLSX
    '@ -split '\r?\n' | Where-Object {
        [datetime]::ParseExact(
            [regex]::Match($_, '\d{14}').Value,
            'yyyyMMddHHmmss',
            [cultureinfo]::InvariantCulture
        ).Date -eq $today
    }
    
    # Results:
    TransferAA_MGH_20211206070920_xlsx.XLSX
    TransferBB_MGH_20211206071130_xlsx.XLSX
    

    因此,您的搜索将如下所示:

    # This filter seem to work OK while testing
    Get-ChildItem -Path . -Filter '*_*_??????????????_????.xlsx'
    
    # So:
    $today = [datetime]::Today
    
    Get-ChildItem -Path 'path/to/TestFolder' -Filter '*_*_??????????????_????.xlsx' |
    Where-Object {
        [datetime]::ParseExact(
            [regex]::Match($_.BaseName, '\d{14}').Value,
            'yyyyMMddHHmmss',
            [cultureinfo]::InvariantCulture
        ).Date -eq $today
    }
    

    如果您希望过滤器更具限制性,您可以使用:

    -Filter 'Transfer??_MGH_??????????????_xlsx.xlsx'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 2011-08-08
      • 2010-09-22
      • 1970-01-01
      • 1970-01-01
      • 2012-06-08
      • 2020-02-13
      相关资源
      最近更新 更多