Skip to content

Instantly share code, notes, and snippets.

@markwragg
Last active May 19, 2017 11:43
Show Gist options
  • Save markwragg/28f92f719e0b2af388dc297a8720c723 to your computer and use it in GitHub Desktop.
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
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