0

I have a need to attempt to convert a date from the registry to a [Datetime] so that I can do operations with it, and the date format is variable, because Autodesk. I also need to be able to throw just in case I have missed some format Autodesk might use. Finding something in the Mayan calendar wouldn't surprise me, Autodesk is THAT inconsistent. Anyway, this is what I started with, and the nested try/catch seemed like a code smell. try { $var1 = (Get-Date) - ([Datetime]::ParseExact(($key.installDate), 'yyyyMMdd', $null)) } catch { try { $var1 = (Get-Date) - ([Datetime]::ParseExact(($key.installDate), 'M/dd/yy', $null)) } catch { try { $var1 = (Get-Date) - ([Datetime]::ParseExact(($key.installDate), 'M/dd/yyyy', $null)) } catch { throw "Date ($($key.installDate)) doesn't match any supported format" } } }

This is what I have now, and I feel like it's a real improvement, but I wonder if there is another, even better, options?

:castDate foreach ($format in @('yyyyMMdd', 'M/dd/yyyy', 'M/dd/yy')) {
    try {
        $var1 = (Get-Date) - ([Datetime]::ParseExact(($key.installDate), $format, $null))
        break :castDate
    } catch {}
}
if (-not $var1) {
   throw "Date ($($key.installDate)) doesn't match any supported format"
}
2
  • ParseExact has a [string[]] $formats overload... Commented Jul 5, 2024 at 13:41
  • also added a TryParseExact example with multiple formats to the duplicated answers, better for this use case. Commented Jul 5, 2024 at 14:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.