使用powershell的compare-object问题

时间:2018-03-15 00:44:53

标签: powershell compare

寻找比较两个system.objects的最佳方法。尝试了compare-object选项,似乎没有给出所需的输出..

> $abc
BGP summary information for VRF default
Router identifier 192.168.0.3, local AS number 7251
Neighbor Status Codes: m - Under maintenance
  Neighbor         V  AS           MsgRcvd   MsgSent  InQ OutQ  Up/Down State  PfxRcd PfxAcc
  10.12.103.119    4  7251               0         0    0    0    5d23h Connect
  10.46.252.121    4  7251               0         0    0    0    5d23h Connect

> $def
BGP summary information for VRF default
Router identifier 192.168.0.3, local AS number 7251
Neighbor Status Codes: m - Under maintenance
  Neighbor         V  AS           MsgRcvd   MsgSent  InQ OutQ  Up/Down State  PfxRcd PfxAcc
  10.12.103.119    4  7251               0         0    0    0    5d23h Active
  10.46.252.121    4  7251               0         0    0    0    5d23h Estab 

> $abc.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

> $def.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

> Compare-Object -ReferenceObject $abc -DifferenceObject $def

InputObject
-----------
BGP summary information for VRF default...
BGP summary information for VRF default...

1 个答案:

答案 0 :(得分:0)

您正在处理字符串[System.String]),而不是[System.Objects] - 后者只是基本类型,即[System.String] 派生自

比较2个多行字符串的最佳方法是逐行比较它们,为此你必须将它们分成几行:

PS> Compare-Object ($abc -split '\r?\n') ($def -split '\r?\n') 

InputObject                                                                     SideIndicator
-----------                                                                     -------------
  10.12.103.119    4  7251               0         0    0    0    5d23h Active  =>           
  10.46.252.121    4  7251               0         0    0    0    5d23h Estab   =>           
  10.12.103.119    4  7251               0         0    0    0    5d23h Connect <=           
  10.46.252.121    4  7251               0         0    0    0    5d23h Connect <=           

=>行(表示差异的输出对象的.SideIndicator属性值)表示RHS独有的行($def),而<=表示专有的行LHS($abc