在 PowerShell 中,如何测试变量是否包含数值? [英] In PowerShell, how can I test if a variable holds a numeric value?

查看:25
本文介绍了在 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]
}

这篇关于在 PowerShell 中,如何测试变量是否包含数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆