Bal Singh
Bal Singh

Reputation: 15

Extracting date from a file name in PowerShell

I have written a PowerShell script to extract the 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 the following error when I run the script, as it recognizes the date before CSV:

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

Can someone advise, please?

Thanks,

Upvotes: 1

Views: 1803

Answers (3)

chris-peterson
chris-peterson

Reputation: 49

if ($filename -match '(?<Timestamp>\d{8})') {
    [DateTime]::ParseExact($Matches.Timestamp, 'ddMMyyyy', [CultureInfo]::InvariantCulture)
}

I gravitate toward regexes with named extraction groups rather than doing string manipulation. The syntax is a bit more fiddly, but the resulting script ends up being more resilient.

Upvotes: 1

Bal Singh
Bal Singh

Reputation: 15

Issue has been fixed by changing from:

[System.DateTime]::ParseExact($fileDateText, "dd/MM/yyyy", [System.Globalization.CultureInfo]::InvariantCulture)

to

$fileDate = [DateTime]::ParseExact("$fileDateText", 'ddMMyyyy',[CultureInfo]::InvariantCulture)

Upvotes: 0

Steven
Steven

Reputation: 7067

I think you may be looking at the wrong array element returning from your split. Also the string you are giving in the overloads for .ParseExact() may be off. This seemed to work in my tests:

$fileDate = ("TBTT_UAT_01012021_000019.csv" -split '_')[2]
[DateTime]::ParseExact($fileDate, "ddMMyyyy", [System.Globalization.CultureInfo]::InvariantCulture)

Returned: Friday, January 1, 2021 12:00:00 AM

If you want to get more granular about the time we'll have to cut up the string file name differently.

Upvotes: 3

Related Questions