剥离PS中的值并比较它是否为整数值 [英] Stripping value in PS and comparing if it is an integer value
问题描述
我正在运行 PS cmdlet get-customcmdlet
生成以下输出
I am running PS cmdlet get-customcmdlet
which is generating following output
Name FreeSpaceGB
---- -----------
ABC-vol001 1,474.201
我有另一个变量 $var=vol
现在,我只想去掉 001
并想检查它是否是一个整数.
I have another variable $var=vol
Now, I want to strip out just 001
and want to check if it is an integer.
我正在使用但得到空值
$vdetails = get-customcmdlet | split($var)[1]
$vnum = $vdetails -replace '.*?(\d+)$','$1'
我的结果应该是整数 001
推荐答案
假设:get-customcmdlet
正在返回一个带有 Name属性的
pscustomobject
对象code> 类型为 string
.
Assumption: get-customcmdlet
is returning a pscustomobject
object with a property Name
that is of type string
.
$var = 'vol'
$null -ne ((get-customcmdlet).Name -split $var)[1] -as [int]
此表达式将根据转换是否成功返回 $true
或 $false
.
This expression will return $true
or $false
based on whether the cast is successful.
如果您的目标是填充零,则需要事后进行(在本例中,我只捕获了原始字符串):
If your goal is to pad zeroes, you need to do that after-the-fact (in this case, I just captured the original string):
$var = 'vol'
$out = ((get-customcmdlet).Name -split $var)[1]
if ($null -ne $out -as [int])
{
$out
}
else
{
throw 'Failed to find appended numbers!'
}
这篇关于剥离PS中的值并比较它是否为整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!