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

前端 未结 14 2082
轮回少年
轮回少年 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: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]
    }
    

提交回复
热议问题