在 PowerShell 中,如何测试变量是否包含数值?

问题描述:

在 PowerShell 中,如何测试变量是否包含数值?

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

目前,我正在尝试这样做,但它似乎总是返回 false.

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

add-type -Language CSharpVersion3 @'
    public class Helpers {
        public static bool IsNumeric(object o) {
            return o is byte  || o is short  || o is int  || o is long
                || o is sbyte || o is ushort || o is uint || o is ulong
                || o is float || o is double || o is decimal
                ;
        }
    }
'@

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

PS> 1 | isNumeric
False

像这样修改你的过滤器:

Modify your filter like this:

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

function 使用 $input 变量来包含管道信息,而 filter 使用特殊变量 $_包含当前管道对象.

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

对于 powershell 语法方式,您可以仅使用过滤器(无添加类型):

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]
}