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

前端 未结 14 2051
轮回少年
轮回少年 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 09:54

    If you want to check if a string has a numeric value, use this code:

    $a = "44.4"
    $b = "ad"
    $rtn = ""
    [double]::TryParse($a,[ref]$rtn)
    [double]::TryParse($b,[ref]$rtn)
    

    Credits go here

    0 讨论(0)
  • 2020-12-16 09:55

    Modify your filter like this:

    filter isNumeric {
        [Helpers]::IsNumeric($_)
    }
    

    function uses the $input variable to contain pipeline information whereas the filter uses the special variable $_ that contains the current pipeline object.

    Edit:

    For a powershell syntax way you can use just a filter (w/o add-type):

    filter isNumeric() {
        return $_ -is [byte]  -or $_ -is [int16]  -or $_ -is [int32]  -or $_ -is [int64]  `
           -or $_ -is [sbyte] -or $_ -is [uint16] -or $_ -is [uint32] -or $_ -is [uint64] `
           -or $_ -is [float] -or $_ -is [double] -or $_ -is [decimal]
    }
    
    0 讨论(0)
  • 2020-12-16 09:56

    If you are testing a string for a numeric value then you can use the a regular expression and the -match comparison. Otherwise Christian's answer is a good solution for type checking.

    function Is-Numeric ($Value) {
        return $Value -match "^[\d\.]+$"
    }
    
    Is-Numeric 1.23
    True
    Is-Numeric 123
    True
    Is-Numeric ""
    False
    Is-Numeric "asdf123"
    False
    
    0 讨论(0)
  • 2020-12-16 09:57

    You can check whether the variable is a number like this: $val -is [int]

    This will work for numeric values, but not if the number is wrapped in quotes:

    1 -is [int]
    True
    "1" -is [int]
    False
    
    0 讨论(0)
  • 2020-12-16 09:58
    PS> Add-Type -Assembly Microsoft.VisualBasic
    PS> [Microsoft.VisualBasic.Information]::IsNumeric(1.5)
    True
    

    http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.information.isnumeric.aspx

    0 讨论(0)
  • 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.]+$")
    }
    
    0 讨论(0)
提交回复
热议问题