Stripping value in PS and comparing if it is an in

2019-06-14 08:41发布

问题:

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