Powershell实用命令(2)

我又来了,今天给大家分享的实用命令是Measure-Object,看这个命令的文字意思就知道是用于统计评估对象的了,那我们来说说他的具体用法

首先我们可以看下这个命令的语法,看看他能支持哪些参数

PS C:\Windows\system32> Get-Command measure-Object -Syntax

Measure-Object [[-Property] <string[]>] [-InputObject <psobject>] [-Sum] [-Average] [-Maximum] [-Minimum] [<CommonParameters>]

Measure-Object [[-Property] <string[]>] [-InputObject <psobject>] [-Line] [-Word] [-Character] [-IgnoreWhiteSpace] [<CommonParameters>]

从上面我们可以看到Measure-Object能够支持求和,求平均值,取最大值,取最小值,统计行数,单词数,字符数,IgnoreWhiteSpace参数是为了让你在统计的时候忽略空白字符(空格,回车)的计数。
下面我们用代码来分别检验一下这些功能

PS C:\Windows\system32> Get-Process | measure -Property vm -Maximum

Count    : 210
Average  : 
Sum      : 
Maximum  : 2238980472832
Minimum  : 
Property : VM

PS C:\Windows\system32> Get-Process | measure -Property vm -Minimum

Count    : 210
Average  : 
Sum      : 
Maximum  : 
Minimum  : 4096
Property : VM

PS C:\Windows\system32> Get-Process | measure -Property vm -Average

Count    : 214
Average  : 1596722333006.95
Sum      : 
Maximum  : 
Minimum  : 
Property : VM

PS C:\Windows\system32> Get-Process | measure -Property vm -sum

Count    : 212
Average  : 
Sum      : 337291811336192
Maximum  : 
Minimum  : 
Property : VM

PS C:\Windows\system32> Get-Content D:\File1.txt | measure -Line -Word -Character

Lines Words Characters Property
----- ----- ---------- --------
    4    20        113         

PS C:\Windows\system32> Get-Content D:\File1.txt | measure -Line -Word -Character -IgnoreWhiteSpace

Lines Words Characters Property
----- ----- ---------- --------
    4    20         97         

PS C:\Windows\system32> Get-Content D:\File1.txt
Learning Powershell Technology

I like Powershell Script Language

Do you like it as me

Fine , let's learn it togather

上面的代码秀出了Measure-Object的功能,就问你,强不强大,厉不厉害,不需要一会调用max,一会调用min,直接一个命令搞定所有

再介绍另外一个比较实用的Measure命令,Measure-Command,这个命令经常用来检测代码的运行时间,通过这个时间,我们可以评估出哪种代码更加优秀,所需时间更短,提升我们代码的执行效率,降低运行代码主机的性能损耗

$Script1={For($i=0;$i -le 100;$i++){Add-Content -Path D:\File1.txt -Value "I want add some word in this file"}}

$Script2={$NW=New-Object System.IO.StreamWriter "d:\file1.txt"; For($i=0;$i -lt 100;$i++){$NW.WriteLine("I Write it again !")};$nw.Close()}

PS C:\Windows\system32> Measure-Command -Expression $Script1 | select TotalMilliseconds

TotalMilliseconds
-----------------
         117.5692

PS C:\Windows\system32> Measure-Command -Expression $Script2 | select TotalMilliseconds

TotalMilliseconds
-----------------
           2.5188

通过Measure-Command 可以评估出同样的结果,但是代码不同,所花费时间是完全不一样的,这样能使我们明白自己的代码是否优秀。

好了,今天就介绍到这,瓜子花生啤酒,客官来一份?

猜你喜欢

转载自blog.51cto.com/thefallenheaven/2170010