Search code examples
powershellpowershell-4.0

How to fetch the file with the file naming convention in Powershell


I want to get today's files with the below file naming convention from the list of other files in the directory using powershell script. Need to match today's date and also the file name.

TransferAA_MGH_20211206070920_xlsx.XLSX
TransferBB_MGH_20211206071130_xlsx.XLSX

I tried below however it's not working. Get-ChildItem -Path Testfolder\*.XLSX | Where-Object {$_.Name -match '(?:^|.*\D)(\d{8})(?:\D.*|$)' -and $Matches[1] -eq ((Get-Date).Date) Thanks for the help.


Solution

  • This should work for you:

    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}
    

    Breaking down the regex pattern:

    • Transfer - literal string
    • [A-Z]{2} - two capital letters
    • _MHM_ - literal string
    • [0-9]{14} - 14 digits
    • _xlsx.XLSX - literal string

    whereas the (Get-Date -Format "yyyyMMdd").Date syntax is used to get today's date formatted properly for comparison.