Stripping value in PS and comparing if it is an integer value

倾然丶 夕夏残阳落幕 提交于 2020-01-03 05:50:12

问题


I am running PS cmdlet get-customcmdlet which is generating following output

Name                         FreeSpaceGB
----                         -----------
ABC-vol001                   1,474.201

I have another variable $var=vol Now, I want to strip out just 001 and want to check if it is an integer.

I am using but getting null value

$vdetails = get-customcmdlet | split($var)[1]
$vnum = $vdetails -replace '.*?(\d+)$','$1'

My result should be integer 001


回答1:


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]

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!'
}


来源:https://stackoverflow.com/questions/51937717/stripping-value-in-ps-and-comparing-if-it-is-an-integer-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!