Powershell sort Array

Source: Internet
Author: User

Note: This is part two of a multiple blog series about working with arrays and hash tables for data storage. In yesterday's Hey, scripting guy! Blog,

Learn simple ways to handle windows powershell Arrays,I discussed creating arrays, indexing into arrays, and two techniques for walking through an array.

Working with specific array elements

One of the interesting things about arrays in Windows powershell is they are able to hold different data types. For example, I can store numbers and strings in the same array as shown here.

PS c: \> $ A = 1, 2, 3, "four"

PS c: \> $

1

2

3

Four

Changing element values

If I need to change an element in array, I Can index into the array by using the square bracket and the index number. To find the upper boundary, I use
Getupperbound Method, and when I have that value, I can easily find the element I need to modify. This technique is shown here.

PS c: \> $ A. getupperbound (0)

3

PS c: \> $ A [3] = 4

PS c: \> $

1

2

3

4

Adding a new element to an existing array

If I want to add an element to an existing array, it might make sense to choose the next index number, and attempt to assign a value in the same way that I change an existing value. when I do this, however, Windows powershell generates an out of range error
Message. This command and error message are shown here.

PS c: \> $ A [4] = 12

Array assignment failed because index '4' was out of range.

At line: 1 CHAR: 4

+ $ A [<4] = 12

+ Categoryinfo: invalidoperation: (4: int32) [], runtimeexception

+ Fullyqualifiederrorid: indexoutofrange

The way to add a new element to an existing array is to use the + = operator as shown here.

$ A + = 12

The commands to create an array, get the upper boundary of an array, change an element in an array, and add a new element to an array are shown here with their associated output.

Searching for a specific value in an array

One question that comes up from time-to-time is, "How do I know whether a value is contained in an array ?" The answer is, once again, rather easy, "use
Contains Operator ". The following two commands use the previusly created
$Array. In the first command, the number 12 is present, and the value
True Returns. In the second example, the array does not contain the number 14; and therefore, the returned value is
False.

PS c: \> $ A-contains 12

True

PS c: \> $ A-contains 14

False

PS c: \>

Sorting an array

Now suppose I need to sort my array. There are actually two ways to do this. The first way to do this is to use
Sort-ObjectCmdlet (SortIs an alias for
Sort-Object
Cmdlet). The second way to sort an array is to use the static
Sort Method fromSystem. Array. NET Framework class.

Use sort and the pipeline

The first technique I will discuss is also the easiest to use. It is the pipeline method. All that this technique requires is to pipe the array to the cmdlet. This technique is shown here.

PS c: \> [int [] $ A =

PS c: \> $ A | sort-Object

1

2

4

5

7

12

The thing to keep in mind is that this does not change the array, it merely changes the display output. if I want to modify the actual array, I need to write the results back to the original array. this technique is shown here.

PS c: \> $ A = $ A | sort

PS c: \> $

1

2

4

5

7

12

The commands to create an array of integers, sort the results with
Sort-Object
Cmdlet, and write the results back to the array are shown in the following image.

Use get-random to create a random array

One of my favorite tricks is to create an array of numbers by using
Get-random
Cmdlet. To do this, I useCount To specify the number of values to select, and I use a range operator to create an array of numbers from which to choose. I then write the random values to a variable. This technique
Is shown here.

$ RND = Get-random-count 10-inputobject (1 .. 100000)

Use the static sort Method

To sort the random numbers, I useSort Static method from
System. Array. NET Framework class. BecauseSort
Is a static method, I need to use a double colon separator between the class name (in square brackets) and the method name. I supply the array of random numbers as an input value. this command is shown here.

[Array]: Sort ($ RND)

What is really interesting is thatSort Static Method, automatically writes the sorted values back to the array that is contained in
$ RNDVariable. The commands to create a random array of numbers, display those values, sort the array, and display the sorted list are shown in the following image.

Measuring the difference in performance

"So, what is the difference between the two ways to sort arrays," you may ask. the difference is that the pipeline way of sorting is probably more intuitive to Windows powershell users. the other difference is that the static
Sort Method fromSystem. ArrayClass is way faster. to check this, I like to use
Measure-commandCmdlet. To ensure I have a large enough data set that will take a decent amount of time to sort, I create two random arrays by using the commands that are shown here.

$ Arraya = Get-random-count 1000000-inputobject (1 .. 1000000)

$ Arrayb = Get-random-count 1000000-inputobject (1 .. 1000000)

Next, I useMeasure-commandCmdlet to measure the two ways of sorting arrays. The two commands are shown here.

Measure-command-expression {$ arraya = $ arraya | sort-object}

Measure-command-expression {[array]: Sort ($ arrayb )}

On my system (which is a fast computer), the First Command takes a little over 40 seconds, whereas the second command takes a little more than 8 seconds. therefore, the second command appears to be five times faster than the first command that uses the pipeline.

The commands that create the two random arrays useMeasure-command
To check the speed of the two commands, and they display the first two numbers in each of the newly sorted arrays, as shown in the following image.

Sorting arrays that contain multiple types

There is one more caveat when it comes to using the two sort methods. Because an array in Windows powershell can contain different types,
Sort-ObjectMethod may be the preferred way of sorting objects. This is because in using the default comparer,
Sort Static Method fails when the array contains different types.

In the following example, I create an array that contains both integers and strings. I then pipe the array to
Sort-ObjectCmdlet (usingSortAs the alias). Next, I attempt to use the static
SortMethod fromSystem. ArrayClass, and that generates an error message.

PS c: \> $ array = 1, 2, 9, 8, 3, "four", "Tree", "cat", "Bat"

PS c: \> $ array | sort

1

2

3

8

9

Bat

Cat

Four

Tree

PS c: \> [array]: Sort ($ array)

Exception calling "sort" with "1" argument (s): "failed to compare two elements in the array ."

At line: 1 CHAR: 14

+ [Array]: Sort <($ array)

+ Categoryinfo: notspecified: (:) [], methodinvocationexception

+ Fullyqualifiederrorid: dotnetmethodexception

PS c: \>

Because an array can contain other objects (besides strings and integers), I decide to perform one additional test, and I therefore store an instance of
System. Diagnostics. Process. NET Framework class in the last element. This command is shown here.

PS c: \> $ array = 1, 2, 9, 8, 3, "four", "Tree", "cat", "Bat", (get-process winword)

PS c: \> $ Array

1

2

9

8

3

Four

Tree

Cat

Bat

Handles NPM (k) PM (k) WS (k) VM (m) CPU (s) ID processname

-----------------------------------------------

463 62 41772 89736 369 39.17 4460 winword

Next, I decide to sort the array. Once again,Sort-ObjectCmdlet comes through with no problems. This output is shown here.

PS c: \> $ array | sort

1

2

3

8

9

Bat

Cat

Four

Handles NPM (k) PM (k) WS (k) VM (m) CPU (s) ID processname

-----------------------------------------------

463 62 41772 89736 369 39.17 4460 winword

Tree

PS c: \>

PT, that is all there is to modifying values in an array, adding to an array, checking to see if an array contains a specific value, and sorting the array. array week will continue tomorrow when I will store different types of objects in an array (including
Other arrays). It will be fun and Educational. See ya!

I invite you to follow me on
Twitter and Facebook. If you have any questions, send email to me
Scripter@microsoft.com, or post your questions on
Official scripting guys Forum. See you tomorrow. Until then, peace.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.