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"
}
ParseExacthas a[string[]] $formatsoverload...TryParseExactexample with multiple formats to the duplicated answers, better for this use case.