2

I have an string array

$list = @("abc-1.0.1-xyz", "abc-1.0.2-xyz", "abc-1.0.3-xyz", "abc-1.0.4-xyz")

and a variable declared as $v = '1.0.2'.

Now I want to compare my array with the variable and get all the strings containing value greater than $v in another array.

For example: in this case abc-1.0.3-xyz and abc-1.0.4-xyz (greater than $v i.e. 1.0.2) will be added to another array.

1 Answer 1

4

I would use simple regex:

$list = 'abc-1.0.1-xyz', 'abc-1.0.2-xyz', 'abc-1.0.3-xyz', 'abc-1.0.4-xyz'
$v = '1.0.2'
$list | % {
    $match = [regex]::Match($_, '\d+\.\d+\.\d+').Value
    if ($match -gt $v) { $_ }
}

Result

abc-1.0.3-xyz
abc-1.0.4-xyz

If you wish to use version comparison (string rules differs, i.e. 10<9), replace condition with following:

if ([version]$match -gt [version]$v) { $_ }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank a ton. This worked. However, it is including abc-1.0.2-xyz in my new array for some reason. But i will trim it off.. No worries about it :)
Replace last line with if ($match -gt $v) { $match }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.