Last active
May 19, 2017 11:43
-
-
Save markwragg/28f92f719e0b2af388dc297a8720c723 to your computer and use it in GitHub Desktop.
PowerShell Function to recurse all levels of a nested object and convert valid date strings to [datetime] properties
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
Function Convert-DateProperties { | |
<# | |
.SYNOPSIS | |
Converts string properties that have 'date' in their name to datetime properties, recursively in all levels of an object. | |
.PARAMETER object | |
The object to convert. | |
.PARAMETER name | |
The string that should be matched in the name property of the object. Default = 'Date'. | |
.EXAMPLE | |
$MyObj | Convert-DateProperties | |
#> | |
Param( | |
[parameter(ValueFromPipeline)] | |
[object]$Object, | |
[string]$Name = 'Date' | |
) | |
Begin { | |
$TypesToExclude = 'System.DateTime', 'System.Boolean', 'System.String', 'System.Int32', 'System.Char' | |
} | |
Process { | |
$Object.Psobject.Properties | ForEach-Object { | |
If ( ($_.Name -match $Name) -and ($_.Value -as [DateTime]) ) { $_.Value = [DateTime]$_.Value } | |
ElseIf ($_.TypeNameOfValue -notin $TypesToExclude) { | |
$Obj = $($Object.$($_.Name)) | |
If ($Obj -ne $null) { Convert-DateProperties -Object $Obj } | |
} | |
} | |
Write-Output $Input | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment