Home > Enterprise >  How to fetch the file with the file naming convention in Powershell
How to fetch the file with the file naming convention in Powershell

Time:12-07

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.

CodePudding user response:

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.

CodePudding user response:

This worked for me, you can give it a try. As an example:

$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

So, your search would look like this:

# 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
}

If you want the filter to be even more restrictive you could use:

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