Last active
September 30, 2024 19:57
-
-
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 file contains hidden or 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
# 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