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

前端 未结 14 2054
轮回少年
轮回少年 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:16
    filter isNumeric {
        $_ -is [ValueType]
    }
    

    -

    1 -is [ValueType]
    True
    "1" -is [ValueType]
    False
    

    -

    function isNumeric ($Value) {
        return $Value -is [ValueType]
    }
    
    isNumeric 1.23
    True
    isNumeric 123
    True
    isNumeric ""
    False
    isNumeric "asdf123"
    False
    

    -

    (Invoke-Expression '1.5') -is [ValueType]
    
    0 讨论(0)
  • 2020-12-16 10:17

    Each numeric type has its own value. See TypeCode enum definition: https://docs.microsoft.com/en-us/dotnet/api/system.typecode?view=netframework-4.8 Based on this info, all your numeric type-values are in the range from 5 to 15. This means, you can write the condition-check like this:

    $typeValue = $x.getTypeCode().value__
    if ($typeValue -ge 5 -and $typeValue -le 15) {"x has a numeric type!"}
    
    0 讨论(0)
提交回复
热议问题