Just a learner
Just a learner

Reputation: 28642

What's the best way to iterate over an array and modify the elements in PowerShell?

I know Ruby has a map! method which do this. In PowerShell currently what I did is:

$new_array = @();
$array | % {
    $new_array += <do something with the currently element $)>;
}
$array = $new_array;

I want to know the best way to do this. Thanks!

Upvotes: 0

Views: 458

Answers (2)

mjolinor
mjolinor

Reputation: 68341

You can also use a filter:

$arr = 1,2,3

 filter addone {$_ +1}
 $arr | addone

Or a filtering function:

function addone {process{$_ +1}}
$arr | addone

Or an anonymous filter:

$addone = {$_ +1}
$addone.isfilter = $true
$arr | &$addone

Edit: The days of that anonymous filter working may be numbered. In the V3 beta that doesn't work any more, and I suspect that's not going to change. It appears the script blocks are compiled as soon as they are created, and the .isfilter property can't be changed after they're compiled.

Upvotes: 0

manojlds
manojlds

Reputation: 301567

Simplest I can think of is

$array | %{ $_ + 1 }

$_ + 1 being the transformation I want.

So you can do:

$new = $array | %{$_ + 1}

or

$array = $array | %{ $_ + 1} 

PS: You can define a map function if you want:

function map ([scriptblock]$script, [array] $a) {

    $a | %{ & $script $_ }

}

map {param($i) $i + 1} 1,2,3

Or write an extension method on System.Array: http://blogs.msdn.com/b/powershell/archive/2008/09/06/hate-add-member-powershell-s-adaptive-type-system.aspx

Upvotes: 6

Related Questions