设为首页 收藏本站
查看: 624|回复: 0

PowerShell Sort Array

[复制链接]

尚未签到

发表于 2017-5-19 13:34:42 | 显示全部楼层 |阅读模式
  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:\> $a
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 theGetUpperBoundmethod, 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:\> $a
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 errormessage. 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 theContainsoperator”. The following two commands use the previously created$a array. In the first command, the number 12 is present, and the valueTruereturns. In the second example, the array does not contain the number 14; and therefore, the returned value isFalse.
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 theSort-Object cmdlet (Sort is an alias for the Sort-Object cmdlet). The second way to sort an array is to use the staticSortmethod from the System.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 = 1,5,7,2,12,4
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:\> $a
1
2
4
5
7
12
  The commands to create an array of integers, sort the results with the 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 the Get-Random cmdlet. To do this, I use Countto 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 techniqueis shown here.
$rnd = Get-Random -Count 10 -InputObject (1..100000)
Use the static Sortmethod
  To sort the random numbers, I use the Sortstatic method from theSystem.Array .NET Framework class. Because Sortis 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 that the Sortstatic method, automatically writes the sorted values back to the array that is contained in the$rnd variable. 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 staticSortmethod from the System.Array class is way faster. To check this, I like to use theMeasure-Command cmdlet. 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 use the Measure-Command cmdlet 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 use Measure-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, theSort-Object method may be the preferred way of sorting objects. This is because in using the default comparer, theSortstatic 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 theSort-Object cmdlet (using Sort as the alias). Next, I attempt to use the staticSort method from the System.Array class, 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 theSystem.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, the Sort-Object cmdlet 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 (includingother 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 atscripter@microsoft.com, or post your questions on theOfficial Scripting Guys Forum. See you tomorrow. Until then, peace.

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-379145-1-1.html 上篇帖子: IronPython与PowerShell比较 下篇帖子: PowerShell基础教程(5)——如何自定义 Windows PowerShell
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表