Omglolyes
Omglolyes

Reputation: 184

How do I do operations with numeric strings inside an array (in powershell)?

So lets say my variable $a is an array containing "1" and "2" as string.

$a = "1", "2"

Now I want to use foreach through a pipeline to subtract 1 from each value, so I'd do something like

$a | foreach{$_ = [int]$_ - 1}

but this seems do nothing, yet produces no error. So $a still contains "1" and "2". I struggle to understand where I went wrong... It's possible if i don't have an array, so this works:

$b = "3"; $b - 2

And it will return 1. So I also tried without "[int]" but it still fails, so I'm guessing it either has to do with the pipeline or my foreach but I wouldn't know why it does that.

Any suggestions?

Upvotes: 1

Views: 221

Answers (2)

mclayton
mclayton

Reputation: 9975

Your foreach isn't mutating the items in your original array like you think it is - you're assigning the calculated value to the context variable $_, not updating the array index.

You can either create a new array with the calculated values as follows:

$a = $a | foreach { [int]$_ - 1 }

or mutate the items in the original array in-place:

for( $i = 0; $i -lt $a.Length; $i++ )
{
    $a[$i] = [int]$a[$i] - 1
}

Note that your second example doesn't quite do what you think either:

PS> $b = "3"; $b - 2
1
PS> $b
3

The $b - 2 part is an expression which is evaluated and echoed out to console - it doesn't change the value of $b because you haven't assigned the result of the expression back to anything.

Upvotes: 3

Dave Sexton
Dave Sexton

Reputation: 11188

Just add the instance variable to the last line of your loop like so:

$a = $a | foreach{$_ = [int]$_ - 1; $_}

Upvotes: 0

Related Questions