Как сравнить ассоциативные массивы в Powershell? - PullRequest
7 голосов
/ 23 декабря 2010

У меня есть два ассоциативных массива

$a = @{"k1"="v1"; "k2"=@{"k21"="v21"}} 

$b = @{"k1"="v1"; "k2"=@{"k21"="v21"}} 

Мне было интересно, есть ли хороший способ сделать сравнение без написания моей собственной функции?

Ответы [ 2 ]

4 голосов
/ 24 декабря 2010

Я не знаю способа, кроме написания функции для сравнения значения каждого ключа (потенциально рекурсивного, если значение является чем-то отличным от примитивного объекта). Однако связанные массивы в PowerShell - это просто типы .NET (System.Collections.Hashtable). Возможно, вы захотите открыть этот вопрос для более широкой аудитории .NET, добавив тег .NET к вашему вопросу.

3 голосов
/ 15 августа 2011

Просто для полноты приведем простую функцию сравнения хеш-таблиц:

function Compare-Hashtable(
  [Hashtable]$ReferenceObject,
  [Hashtable]$DifferenceObject,
  [switch]$IncludeEqual
) {
  # Creates a result object.
  function result( [string]$side ) {
    New-Object PSObject -Property @{
      'InputPath'= "$path$key";
      'SideIndicator' = $side;
      'ReferenceValue' = $refValue;
      'DifferenceValue' = $difValue;
    }
  }

  # Recursively compares two hashtables.
  function core( [string]$path, [Hashtable]$ref, [Hashtable]$dif ) {
    # Hold on to keys from the other object that are not in the reference.
    $nonrefKeys = New-Object 'System.Collections.Generic.HashSet[string]'
    $dif.Keys | foreach { [void]$nonrefKeys.Add( $_ ) }

    # Test each key in the reference with that in the other object.
    foreach( $key in $ref.Keys ) {
      [void]$nonrefKeys.Remove( $key )
      $refValue = $ref.$key
      $difValue = $dif.$key

      if( -not $dif.ContainsKey( $key ) ) {
        result '<='
      }
      elseif( $refValue -is [hashtable] -and $difValue -is [hashtable] ) {
        core "$path$key." $refValue $difValue
      }
      elseif( $refValue -ne $difValue ) {
        result '<>'
      }
      elseif( $IncludeEqual ) {
        result '=='
      }
    }

    # Show all keys in the other object not in the reference.
    $refValue = $null
    foreach( $key in $nonrefKeys ) {
      $difValue = $dif.$key
      result '=>'
    }
  }

  core '' $ReferenceObject $DifferenceObject
}

Пример вывода:

> $a = @{ 'same'='x'; 'shared'=@{ 'same'='x'; 'different'='unlike'; 'new'='A' } }
> $b = @{ 'same'='x'; 'shared'=@{ 'same'='x'; 'different'='contrary' }; 'new'='B' }
> Compare-Hashtable $a $b

InputPath          ReferenceValue   DifferenceValue   SideIndicator
---------         --------------   ---------------   -------------
shared.different   unlike           contrary          <>
shared.new         A                                 <=
new                                 B                =>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...