检查字符串 can/cannot 是否被转换为 int/float

Checking if a string can/cannot be converted to int/float

我正在使用 PowerShell 7.1.4,我想检查一个字符串是否可以转换为数字。

类似于:

$age = Read-Host "age"

if(![int]$age) {
    Write-Host "$age is not a number"
}

我来自 JavaScript 所以不要介意“!”如果错了,我才刚开始学PowerShell

如果无法转换为 RHS 类型,您可以使用 $age -as [int],其中 returns $null,因此 $null -eq ($age -as [int]) 只有 $true 如果转换是 not 可能(参见 -asconditional type conversion operator ):

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] 转换转换 emptyblank(全空白)字符串(以及 $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] cast 的操作数可以 not被转换为指定的类型。 -as 运算符的使用避免了这个问题。

为了完整起见:可以 - 尽管此处不建议 - 使用 try { ... } catch { ... } statement enclosed in $(), the subexpression operator 来捕获错误:

if ($null -eq $(try { [int] $age } catch {})) { Write-Host "$age is NOT a number." }