PowerShell 技能连载 - 类型转换机制
基本转换方法
1 | # 隐式转换 |
应用场景
字符串解析:
1
2
3
4$userInput = Read-Host "请输入数字"
if ($userInput -as [int]) {
# 安全转换成功
}类型验证:
1
2
3
4
5
6
7try {
[ValidateScript({$_ -as [uri]})]
[uri]$url = "https://blog.vichamp.com"
}
catch {
Write-Warning "无效的URL格式"
}
最佳实践
- 优先使用-as操作符进行安全转换
- 处理文化差异(CultureInfo)
- 自定义转换逻辑:
1
2
3
4
5
6
7
8
9
10class Temperature {
[double]$Celsius
static [Temperature] Parse($input) {
if ($input -match "(\d+)°C") {
return [Temperature]@{Celsius = $matches[1]}
}
throw "无效的温度格式"
}
}
PowerShell 技能连载 - 类型转换机制
http://blog.vichamp.com/2024/12/09/powershell-type-conversion/