在PowerShell中,如何测试变量是否包含数值?
目前,我正试图这样做,但似乎总是回归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
Run Code Online (Sandbox Code Playgroud)
top*_*eve 37
您可以检查变量是否是这样的数字: $val -is [int]
这适用于数值,但如果数字用引号括起来则不行:
1 -is [int]
True
"1" -is [int]
False
Run Code Online (Sandbox Code Playgroud)
jos*_*hls 24
如果要测试字符串的数值,则可以使用正则表达式和-match
比较.否则Christian的答案是类型检查的一个很好的解决方案.
function Is-Numeric ($Value) {
return $Value -match "^[\d\.]+$"
}
Is-Numeric 1.23
True
Is-Numeric 123
True
Is-Numeric ""
False
Is-Numeric "asdf123"
False
Run Code Online (Sandbox Code Playgroud)
CB.*_*CB. 23
像这样修改你的过滤器:
filter isNumeric {
[Helpers]::IsNumeric($_)
}
Run Code Online (Sandbox Code Playgroud)
function
使用$input
变量来包含管道信息,而filter
使用$_
包含当前管道对象的特殊变量.
编辑:
对于powershell语法方式,您只能使用过滤器(没有添加类型):
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]
}
Run Code Online (Sandbox Code Playgroud)
小智 17
你可以这样做:
$testvar -match '^[0-9]+$'
Run Code Online (Sandbox Code Playgroud)
要么
$testvar -match '^\d+$'
Run Code Online (Sandbox Code Playgroud)
如果$ testvar是一个数字,则返回"True"
x0n*_*x0n 10
PS> Add-Type -Assembly Microsoft.VisualBasic
PS> [Microsoft.VisualBasic.Information]::IsNumeric(1.5)
True
Run Code Online (Sandbox Code Playgroud)
http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.information.isnumeric.aspx
-is和-as运算符需要一个可以比较的类型.如果您不确定类型是什么,请尝试评估内容(部分类型列表):
(Invoke-Expression '1.5').GetType().Name -match 'byte|short|int32|long|sbyte|ushort|uint32|ulong|float|double|decimal'
Run Code Online (Sandbox Code Playgroud)
好的或坏的,它也可以对十六进制值起作用(Invoke-Expression'0xA'...)
如果要检查字符串是否具有数字值,请使用以下代码:
$a = "44.4"
$b = "ad"
$rtn = ""
[double]::TryParse($a,[ref]$rtn)
[double]::TryParse($b,[ref]$rtn)
Run Code Online (Sandbox Code Playgroud)
学分到这里
filter isNumeric {
$_ -is [ValueType]
}
Run Code Online (Sandbox Code Playgroud)
-
1 -is [ValueType]
True
"1" -is [ValueType]
False
Run Code Online (Sandbox Code Playgroud)
-
function isNumeric ($Value) {
return $Value -is [ValueType]
}
isNumeric 1.23
True
isNumeric 123
True
isNumeric ""
False
isNumeric "asdf123"
False
Run Code Online (Sandbox Code Playgroud)
-
(Invoke-Expression '1.5') -is [ValueType]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
113489 次 |
最近记录: |