1

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?

0

2 Answers 2

3

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.

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

Comments

0

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

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

1 Comment

I suggest $a = $a | foreach{ [int]$_ - 1 }, which is not only more more concise and efficient, it also avoids assigning to an automatic variable ($_), which should generally be avoided.

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.