SoFunction
Updated on 2025-03-10

Powershell tips: Use Update-TypeData to extend the type system

script

Update-TypeData -TypeName '' -MemberName 'Time' -MemberType 'ScriptProperty' -Value {
  $timeAliasArray='Zi Chou Yin Mao Chen Si Wu Wei Shen You Xu Hai'
  $hour = $
  [int]$index=0
  if($hour -eq 22){ $index=11 }
  else{
    $index=[math]::Floor( ( $hour+1 ) % 23 / 2 )
     }
 return $timeAliasArray[ $index ] + "hour"
}

Demo

After the above command is executed, DateTime has an additional attribute. Let's verify:

PS> (get-date).Time
Mid-time
PS> $t=Get-Date -Hour 17
PS> $t.Time
Time of You

Summarize

Compared with Add-Member, Update-TypeData extends the type of the former and the instance of the latter.
How to permanently expand the type can be placed in the Profile file or directly modified ETS file.