11

I'm trying to convert a string that looks like this,

    2,3,4,5,6,20..30

to an array of integers. Here is the code I currently have:

[string]$a = "2,3,4,5,6,7"
[array]$b = $a.split(",")
[array]$c = foreach($number in $b) {([int]::parse($number))}

Which works, but not for the range of 20..30. How do I get that part working?

3 Answers 3

9

You can use the Invoke-Expression cmdlet to interpret the 10..30 bit, if the [int]::Parse() method call fails.

Here is a complete, working sample.

[string]$a = "2,3,4,5,6,7,10..30";
[array]$b = $a.split(",");
[array]$c = foreach($number in $b) {
    try {
        [int]::parse($number)
    }
    catch {
        Invoke-Expression -Command $number;
    }
    }

$c;
Sign up to request clarification or add additional context in comments.

Comments

7

One-liner (just for fun):

$c = "2,3,4,5,6,7,10..30".split(',') | % {iex $_}

6 Comments

Well done, but without looking at trevor's code and explanation I wouldn't have been able to figure out what you were doing here!
@ImpossibleSqui Thanks but I sincerely hope that you will not use a code that generates an exception when it is not necessary ;)
I can't say no to one-liners...after experimenting with both your codes, I ended up using yours for it's simplicity. Thanks again!
@ImpossibleSqui Glad to help! You can always change your choice answer ;)
If string not contains comma - split still made it array with one element - it's ok. But after converting into number it made Int32 variable not Array :(
|
0

Inside of a string, your .. is taken as-is and is not expanded to a range.

So $a = "1 .. 5" is actually 1 .. 5 and not 1, 2, 3, 4, 5.

To make your program work, you will have to tokenize not only on , but also on .. and then expand.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.