Windows Powershell分析和比较管道结果

使用Measure-Object和Compare-Object可以统计和对比管道结果。Measure-Object允许指定待统计对象的属性。Compare-Object可以对比对象前后的快照。

统计和计算

使用Measure-Object可以对对象的属性求最小值、最大值、平均值、和。例如要查看当前目录文件占用空间的情况。

PS C:Powershell> ls | measure length
Count  : 19
Average :
Sum   :
Maximum :
Minimum :
Property : length

PS C:Powershell> ls | measure length -Average -Sum -Maximum -Minimum
Count  : 19
Average : 53768.8421052632
Sum   : 1021608
Maximum : 735892
Minimum : 0
Property : length

使用Measure-Object还可以统计文本文件中的字符数,单词数,行数
例如我们可以把下面的文本保存到:word.txt 。

Retirement Anxiety Spreads Among the One Percent
Report: Green Monday a Boon for Online Shopping
5 Lesser-Known Ways to Boost Your Credit Score
PS C:Powershell> Get-Content .word.txt | measure -Line -Word -Character
Lines Words Characters Property
----- ----- ---------- --------
  3  23    141

比较对象

有时需要比较前后两个时间段开启了那些进程,服务状态有什么变化。类似这样的工作可以交给Compare-Object。

比较不同的时间段
可以先将所有开启的进程信息快照保存到一个变量中,过一段时间,再保存一份新的进程快照,然后就可以通过Compare-Object进行对比了。

PS C:Powershell> $before=Get-Process
PS C:Powershell> $after=get-process
PS C:Powershell> Compare-Object $before $after

InputObject               SideIndicator
-----------               -------------
System.Diagnostics.Process (notepad)  =>
System.Diagnostics.Process (notepad)  =>
System.Diagnostics.Process (AcroRd32)

$before 是一个数组存储了当前所有的Process对象,Compare-Object的结果有两个列:InputObject为前后不一致的对象,SideIndicator为不一致状态,=>表示新增的对象,结合上面的例子分析:在before和after的时间段有3个进程(AcroRd32,AcroRd32,prevhost)关闭了,有2个进程开启了(notepad,notepad)。

检查对象的变化

Compare-Object并不仅仅能比较对象组中的是否新增和减少了对象,它还可以比较每个对象的属性变化,因为它有一个参数-property 。

PS C:PowerShell> Get-Service wsearch

Status  Name        DisplayName
------  ----        -----------
Running wsearch      Windows Search

PS C:PowerShell> $svc1=Get-Service wsearch
PS C:PowerShell> $svc1.stop()
PS C:PowerShell> $svc2=Get-Service wsearch
PS C:PowerShell> Compare-Object $svc1 $svc2 -Property Status,Name

          Status Name            SideIndicator
          ------ ----            -------------
       StartPending wsearch          =>
          Running wsearch

比较文件的内容

对于文本文件可以通过Get-Content进行读取,并且将文件以行为单位保存为一个数组,这时依然可以通过Compare-Object进行比较。下面的例子创建两个不同的文本文件,然后通过Compare-Object比较两个文件的Get-Content结果。

PS C:PowerShell> "Hellow
>> Power
>> Shell" >a.txt
>>
PS C:PowerShell> "Hollow
>> Shell
>> Linux" >b.txt
>>
PS C:PowerShell> Compare-Object (Get-Content .a.txt) (Get-Content .b.txt)
InputObject SideIndicator
----------- -------------
Hollow   =>
Linux     =>
Hellow

保存快照以便后期使用

上面的例子都是把对象保存在变量中,变量有一个缺点就是一旦Powershell退出或者电脑关闭变量都会消失。所以最好的方法就是把对象保存到磁盘文件中。怎样把对象序列化成一个文件,Powershell提供了一条命令:Export-Clixml,可以完成此工作,还有一条反序列化的命令Import-Clixml。这样可以使Compare-object的命令更方便。例如一个月前保存一个$before对象,一个月后比较都可以。

PS C:PowerShell> Get-Process | Export-Clixml before.xml
PS C:PowerShell> $before=Import-Clixml .before.xml
PS C:PowerShell> $after=Get-Process
PS C:PowerShell> Compare-Object -ReferenceObject $before -DifferenceObject $after