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

前端 未结 14 2078
轮回少年
轮回少年 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条回答
  •  -上瘾入骨i
    2020-12-16 10:01

    Thank you all who contributed to this thread and helped me figure out how to test for numeric values. I wanted to post my results for how to handle negative numbers, for those who may also find this thread when searching...

    Note: My function requires a string to be passed, due to using Trim().

    function IsNumeric($value) {
    # This function will test if a string value is numeric
    #
    # Parameters::
    #
    #   $value   - String to test
    #
       return ($($value.Trim()) -match "^[-]?[0-9.]+$")
    }
    

提交回复
热议问题