Search code examples
powershelltypesconsole

How to change Get-Date commandlet default result value in Powershell


Get-Date returns something like "26 July 2023 12:54:21"

this is the default representation (it is the content of property .DateTime which is a string)

how can I set the default result of Get-Date to .Year (for example)

  • This is a generic types question but I think is better to put it this way
  • Update-TypeData did not solve this problem... just for Format-List/Table/Wide...
  • I know I can do (get-date).year... that is not the point!

Solution

  • Note:

    • This answer addresses how to change the representation of [datetime] (System.DateTime) instances (such as output by Get-Date) when converted to strings, either explicitly or implicitly.

    • This has no impact on using [datetime] instances as themselves.


    You can use Update-TypeData to both modify the .DateTime ScriptProperty ETS (Extended Type System property of [datetime] instances and to override the type-native .ToString() method with a ScriptMethod ETS property, but there's a wrinkle:

    # Override .ToString()
    Update-TypeData -Force -TypeName System.DateTime -MemberType ScriptMethod -MemberName ToString -Value {
      [string] $this.Year
    }
    # Redefine .DateTime
    Update-TypeData -Force -TypeName System.DateTime -MemberType ScriptProperty -MemberName DateTime -Value {
      $this.ToString() # This calls the overridden .ToString() method.
    }
    

    Now, the .DateTime property of [datetime] instances reports just the instance's year, and so do (explicit and implicit) .ToString() calls:

    # === These work:
    # Use of the redefined .DateTime via the formatting system.
    Get-Date
    [datetime]::Now
    # Use of the overridden .ToString() method.
    (Get-Date).ToString()
    Write-Host (Get-Date) # implicit .ToString() call 
    [pscustomobject] @{ Date = (Get-Date) } # implicit .ToString() call on nested values
    
    # === Due to the BUG mentioned above, the following do NOT work.
    # They use the original .ToString() format.
    "$(Get-Date)"
    [string] (Get-Date)