In PowerShell, how can I test if a variable holds a numeric value?

前端 未结 14 2132
轮回少年
轮回少年 2020-12-16 09:15

In PowerShell, how can I test if a variable holds a numeric value?

Currently, I\'m trying to do it like this, but it always seems to return false.

14条回答
  •  没有蜡笔的小新
    2020-12-16 10:07

    $itisint=$true
    try{
     [int]$vartotest
    }catch{
     "error converting to int"
     $itisint=$false
    }
    

    this is more universal, because this way you can test also strings (read from a file for example) if they represent number. The other solutions using -is [int] result in false if you would have "123" as string in a variable. This also works on machines with older powershell then 5.1

提交回复
热议问题