I encountered a bizarre issue with date conversion. Everything is working as expected in my local PowerShell, but something goes wrong when the same code is running in a pipeline. The goal is to capture the date from the title and convert it to a different format.
I have a title like:
$title = "Update 11-02-2024"
I am extracting the date from the title:
$date = ([regex]::Matches($title, '(\d{2}-\d{2}-\d{4})')).Value
Converting the old date to a new format:
$newDate = Get-Date $date -UFormat "%B %d, %Y"
The new date is:
February 11, 2024
This is the right format for me, looks like it is working. When the code is running via the pipeline the result is:
Update November 02, 2024
This is what the pipeline runs:
if ($itemTitle -match 'Update') {
$date = ([regex]::Matches($itemTitle, '(\d{2}-\d{2}-\d{4})')).Value
$newDate = Get-Date $date -UFormat "%B %d, %Y"
$newTitle = $itemTitle.Replace($Matches[0],"Dictionaries Update").Replace($date,$newDate)
Write-host "The new title is: $newTitle"
}
The pipeline runs a task that runs the script with the same code. What am I missing?
This difference in parsing behavior likely occurs because the pipeline is being executed on a runner machine with en-US
default locale, so the default date format is MM-dd-yyyy.
Use [datetime]::ParseExact
to always use a specific format when parsing dates:
$newDate = [datetime]::ParseExact($date, 'dd-MM-yyyy', $null) |Get-Date -UFormat "%B %d, %Y"