我正在使用PowerShell 7.1.4,我想检查字符串是否可以转换为数字。
类似:
$age = Read-Host "age"
if(![int]$age) {
Write-Host "$age is not a number"
}
我来自JavaScript,所以不要介意"!"如果它是错误的,我刚刚开始学习PowerShell。
您可以使用$age -as [int]
,如果不可能转换为RHS类型,则返回$null
,因此,如果转换不可能,则$null -eq ($age -as [int])
仅为$true
(参见-as
)。(条件类型转换操作符):
if ($null -eq ($age -as [int])) { Write-Host "$age is NOT a number." }
如果你也想保存转换后的值,你可以利用PowerShell使用赋值作为表达式的能力:
if ($null -eq ($ageNumber = $age -as [int])) { Write-Host "$age is NOT a number." }
警告:-as
和[int]
强制转换将空或空白(全空白)字符串(以及$null
)转换为0
。(试试'' -as [int]
、' ' -as [int]
和$null -as [int]
)。
避免:
- 要么:使用下一节 所示的。net方法
- 或:添加一个额外的检查来检测这些情况:
if ('' -eq $age.Trim() -or $null -eq ($age -as [int])) { Write-Host "$age is NOT a number." }
不太符合powershell习惯,但更严格的替代将使用[int]::TryParse()
.NET方法:
if (-not [int]::TryParse($age, [ref] $null)) { Write-Host "$age is NOT a number." }
如果您还希望保存转换后的值,则初始化一个输出变量并传递它以代替$null
:
$ageNumber = $null # Initialize the output variable (type doesn't matter).
if (-not [int]::TryParse($age, [ref] $ageNumber)) { Write-Host "$age is NOT a number." }
如上所示,此方法不将空字符串和空白字符串识别为整数。
至于你试过的:
!
是一个有效的PowerShell操作符;别名为-not
PowerShell隐式地将其操作数转换为布尔值(
[bool]
),所以关于整数的警告是! 0
也是$true
,即使0
是一个有效的整数。关于PowerShell隐式到布尔值转换的概述,请参阅答案的底部部分。
问题是[int]
强制转换导致语句终止错误,当其操作数可以不转换为指定类型时。-as
操作符的使用避免了这个问题。
为了完整起见:可以(尽管这里不建议)使用子表达式操作符$()
中包含的try { ... } catch { ... }
语句来捕获错误:
if ($null -eq $(try { [int] $age } catch {})) { Write-Host "$age is NOT a number." }