Last active
June 29, 2020 20:24
-
-
Save DBremen/962daf185f2e12900f39ac0349d85132 to your computer and use it in GitHub Desktop.
PowerShell custom argument transformation attribute for DateTime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DateTransformAttribute : System.Management.Automation.ArgumentTransformationAttribute { | |
# property to take additional format strings for transformations | |
[string[]]$AdditionalFormatStrings | |
# default constructor: | |
DateTransformAttribute() : base() { } | |
# 2nd constructor with parameter AdditionalFormatStrings | |
DateTransformAttribute([string[]]$AdditionalFormatStrings) : base() { | |
$this.AdditionalFormatStrings = $AdditionalFormatStrings | |
} | |
# Transform() method is called whenever there is a variable or parameter assignment. | |
[object] Transform([System.Management.Automation.EngineIntrinsics]$engineIntrinsics, [object] $inputData) { | |
if ($inputData -as [datetime]) { | |
# return as-is: | |
return ($inputData -as [datetime]) | |
} | |
# get the provided format strings first for them to take precedence | |
$dateFormatStrings = $this.AdditionalFormatStrings | |
# add the static date format strings | |
$dayFirstFormats = 'd/M h:mtt', 'dd/MM hh:mmtt', 'dd/MM hh:mm:ss tt' | |
# add same with '.' as delimiter | |
$dayFirstFormats = $dayFirstFormats.foreach{ $_; $_.Replace('/', '.') } | |
$monthFirstFormats = 'M/d h:mtt', 'MM/dd hh:mmtt', 'MM/dd hh:mm:ss tt' | |
# check if the local date is in M/d or d/M format | |
# check for this format first | |
if ('14/6' -as [datetime]) { | |
# local date is d/M | |
$dateFormatStrings += $dayFirstFormats + $monthFirstFormats | |
} | |
else { | |
$dateFormatStrings += $monthFirstFormats + $dayFirstFormats | |
} | |
#try to convert a provided string with ParseExact using the different format strings | |
if ($inputData -is [string]) { | |
foreach ($format in $dateFormatStrings) { | |
try { | |
$newDate = [datetime]::ParseExact($inputData, $format, $Null) | |
} | |
catch { | |
# if the conversion attempt fails keep trying the other formats | |
continue | |
} | |
# if the conversion succeeds return the date | |
if ($newDate) { return $newDate } | |
} | |
} | |
# conversion faild throw an exception. | |
throw [System.InvalidOperationException]::new('No valid date time.') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment