Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sba923/ddc6e300e2bbe3f01d1ee20276d0cfe4 to your computer and use it in GitHub Desktop.
Save sba923/ddc6e300e2bbe3f01d1ee20276d0cfe4 to your computer and use it in GitHub Desktop.
Convert all DateTime properties of objects on the pipeline to strings including milliseconds, to work around Export-CSV's limitation
# this is one of Stéphane BARIZIEN's public domain scripts
# the most recent version can be found at:
# https://gist.github.com/sba923/ddc6e300e2bbe3f01d1ee20276d0cfe4#file-convert-datetimepropertiestostringwithmilliseconds-ps1
#requires -Version 7.3
# this rewrites the objects on the pipeline so that DateTime members are replaced with a string representation including milliseconds
# to work around the fact Export-CSV doesn't include milliseconds (see https://github.com/PowerShell/PowerShell/issues/19536)
# compute millisecond-aware version of the current datetime format
$format = "{0:" + (Get-Culture).DateTimeFormat.ShortDatePattern + ' ' + (Get-Culture).DateTimeFormat.LongTimePattern + '.fff' + "}"
foreach ($object in $input)
{
# preserve order of properties
$properties = $object.PSObject.Properties.Name
$newobject = [PSCustomObject]@{
}
# convert all members that are timestamps to strings with milliseconds
$object | Get-Member -MemberType NoteProperty | Foreach-Object {
$member = $_
if ($member.Definition -match '^System\.DateTime\s+')
{
Add-Member -InputObject $newobject -MemberType $member.MemberType -Name $member.Name -Value ($format -f $object.($member.Name))
}
else
{
Add-Member -InputObject $newobject -MemberType $member.MemberType -Name $member.Name -Value $object.($member.Name)
}
}
$newobject | Select-Object $properties
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment