2

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This code is fetching all the files that matches "Transfer[A-Z]{2}_MGH_[0-9]{14}_xlsx.XLSX". But i just need today's files. Please suggest.
1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.