Extracting date from a file name in powershell

I have written a powershell script to extract date from filenames and delete based on that.

Sample file name : TBTT_UAT_01012021_000019.csv

Code to extract date :

$fileDateText = ($filename -split '_')[4] $fileDate = [System.DateTime]::ParseExact($fileDateText, "dd/MM/yyyy", [System.Globalization.CultureInfo]::InvariantCulture)

But I am getting following error when run it as it recognizes date before CSV:

String ‘000019.csv’ was not recognized as a valid DateTime.: FormatException

Can someone advise please?

Thanks,

Rinku,
Welcome to the forum. :wave:t4:

Indexes in PowerShell start with 0 (zero). So you should use …

($filename -split '_')[2]

… to extract the third element from the splitted file name. :wink:

Regardless of that - could you please format your code as code using the preformatted text button ( </> )?

Thanks in advance.

BTW: When you crosspost the same question at the same time to different forums you should at least post links to the other forums along with your question to avoid people willing to help you making their work twice or more.

Thanks