Get-Date 返回类似“2023 年 7 月 26 日 12:54:21”的内容
这是默认表示
(它是属性 .DateTime 的内容,它是一个字符串)
如何将 Get-Date 的默认结果设置为 .Year(例如)
注:
这个答案解决了如何在转换为字符串
时显式或隐式地更改
[datetime]
(System.DateTime
) 实例的表示(例如 Get-Date
的输出)。
这对使用
[datetime]
实例本身没有影响。
.DateTime
ScriptProperty
ETS(
[datetime]
实例的扩展类型系统属性)并覆盖类型原生
.ToString()
方法ScriptMethod
ETS 财产,但有一个问题:
[string]
casts 和 PowerShell 的 string interpolation 的上下文中,至少存在 PowerShell 7.3.9(截至撰写本文时为当前版本)(在 expandable 内部(双引号))字符串 (
"..."
)) ETS
.ToString()
方法出人意料地不 受到尊重 - 请参阅 GitHub 问题 #14561;遗憾的是,这个 bug 似乎无法修复。
# 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.
}
现在,.DateTime
实例的
[datetime]
属性仅报告实例的年份,
.ToString()
调用也是如此(显式和隐式):
# === 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)