Skip to content

Data Types(数据类型)

PowerShell 基于 .NET,对象即一等公民。常见标量类型:

  • 数值:[int] [long] [double] [decimal] [byte]
  • 文本:[string](不可变)
  • 日期/时间:[datetime] [timespan]
  • 布尔:[bool]$true/$false
  • 其他:脚本块 [scriptblock]、正则 [regex]、XML [xml]

集合类型:

  • 数组:[object[]] 或强类型如 [int[]]
  • 哈希表:[hashtable]、有序哈希表 [ordered]
  • 列表/字典(高性能):[System.Collections.Generic.List[T]][System.Collections.Generic.Dictionary[K,V]]

类型加速器(常用别名)示例:[int] [string] [datetime] [timespan] [pscustomobject] [hashtable] [ordered] [regex] [xml]

类型转换(强制与解析):

powershell
[int]'42'                 # 42
[double]'3.14'            # 3.14(注意小数点与区域设置)
[decimal]'19.99'
[datetime]'2025-01-01'
[timespan]'1:30:00'       # 1 小时 30 分
# 解析 API(可控文化/格式):
[datetime]::ParseExact('2025-01-01','yyyy-MM-dd',$null)

空值与判空:

powershell
$null -eq $x   # 推荐写法,避免在 $x 为 $null 时调用其 .Equals()
[string]::IsNullOrEmpty($s)
[string]::IsNullOrWhiteSpace($s)

自定义对象(结构化输出):

powershell
[pscustomobject]@{
  Name='Alice'; Age=30; Joined=[datetime]'2024-05-01'
}

类型判断与转换:

powershell
1 -is [int]           # True
'123' -as [int]       # 123;失败返回 $null 而非报错
'abc' -as [int]       # $null

可空值类型(.NET Nullable):

powershell
[Nullable[int]]$n = $null   # 或 [int]?$n 在 PowerShell 7+
$n = 5

检查成员与探索类型:

powershell
Get-Date | Get-Member    # 查看类型与可用属性/方法

建议:

  • 需要精确小数运算用 [decimal],避免二进制浮点误差。
  • 读写文件/网络返回的对象,先用 Get-Member 观察后再处理。
  • 大规模数据处理优先选用强类型集合(List/Dictionary)以获得更好性能。

本站内容仅供学习和研究使用。