剥离PS中的值并比较它是否为整数值 [英] Stripping value in PS and comparing if it is an integer value

查看:63
本文介绍了剥离PS中的值并比较它是否为整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行 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 正在返回一个带有 Namepscustomobject 对象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屋!

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