# PowerTip: The Finer Points of Finessing an Array

### PowerTip: The Finer Points of Finessing an Array

Rate This

Summary: Learn how to replace items in an array and how to sort an array.

I need to replace the “2” with “12” in the \$array variable shown here:

\$array = "1","2","3","4"

How can I do this?

1. \$array=[regex]::replace(\$array,"2","12")
2. \$array = \$array -replace "2","12"
3. \$array.SetValue("12",1)

I have an array defined in the \$array variable shown here.

\$array = 2,5,9,12,3,5

What is the easiest way to sort the array?

1. Sort the array by using the sort static method from the [array] .NET Framework class.

[array]::sort(\$array)

2. Pipe the array to the Sort-Object cmdlet, and store the results back in the \$array variable.

\$array = \$array | sort

• In the first question, what about:

\$array[1] = "12"

• It is we like arrays day.  Hooray!

# find anything

18:39 PS>\$a='joe','jeff','sam','ed','tom'

18:39 PS>[array]::BinarySearch(\$a,'sam')

2

# sort wiout assignment -  very fast

[array]::Sort(\$a)

# one of the most powerful array comamnds

18:55 PS>\$n=1,2,3,4,5,6,7,8,9,0

18:56 PS>[array]::Reverse(\$n)

18:56 PS>\$n

0

9

8

7

6

5

4

3

2

1