Format a datetime in PowerShell to JSON as \/Date(1411704000000)\/

前端 未结 3 1213
感动是毒
感动是毒 2020-12-31 18:49

I want to get the current date as a string in the following format:

\\/Date(1411762618805)\\/

I have been fighting with PowerShell and have trie

3条回答
  •  庸人自扰
    2020-12-31 19:33

    There are two problem properties here, DateTime and DisplayHint and both require a different solution. The DateTime property is a ScriptProperty attached by the extended type system, so it exists on all DateTime objects automatically. You can remove it from all DateTime objects in the current session via Remove-TypeData

    Get-TypeData System.DateTime | Remove-TypeData
    

    The DisplayHint property is a NoteProperty that is added by the Get-Date cmdlet. I know of no way to suppress this from serialization. You can remove it explicitly from the DateTime:

    Get-Date | foreach { $_.PSObject.Properties.Remove("DisplayHint"); $_ } | ConvertTo-Json
    

    which will output

    "\/Date(1411846057456)\/"
    

    This is current date and time, if you only want the date you can do this

    Get-Date | select -ExpandProperty Date | ConvertTo-Json
    

    Here we don't have to remove the DisplayHint because it was not attached by Get-Date.

    Don't even get me started on the hoops you will have to jump through to convert back to the proper date time object.

提交回复
热议问题