Tony
Tony

Reputation: 9581

Hashset to keys and values

I have a problem in my script:

here I set a var remotefilehash:

$remotefilehash = $remotefiles -replace '^[a-f0-9]{32}(  )', '$0=  ' | ConvertFrom-StringData

this creates a hashtable

I then compare those hash's to what I have locally in a hashset

# Create a hash set from the local hashes.

$localHashSet = [System.Collections.Generic.HashSet[string]] $localmd5

# Loop over all remote hashes to find those not among the local hashes.
$diffmd5 = $remotefilehash.Keys.Where({ -not $localHashSet.Contains($_) })

this gets me the hashkeys but I subsequently also need to get the hash values for those keys that are found in the above where ...

Upvotes: 2

Views: 816

Answers (1)

mklement0
mklement0

Reputation: 438143

this creates a hashtable

Actually, it creates an array of hashtables, because ConvertFrom-StringData turns each pipeline input object into a separate hashtable.

To create a single hashtable, join the input lines to form a single string first - note how -join "`n" is applied to the result of the -replace operation in order to form a single, multi-line string:

$remotefilehash = 
  ($remotefiles -replace '^[a-f0-9]{32}(  )', '$0=  ' -join "`n") |
     ConvertFrom-StringData

To enumerate the key-value pairs instead of just the keys (.Keys) of a hashtable(-like) object, you need to use its .GetEnumerator() method:

$diffmd5 = 
  $remotefilehash.GetEnumerator().Where({ -not $localHashSet.Contains($_.Key) })

The reason that an enumerator must be requested explicitly is that PowerShell by default considers a hashtable/dictionary a single object that is passed as a whole through the pipeline / passed to enumeration methods such as the .Where() and .ForEach() array methods.

Note that the output of the above command is not itself a hashtable, but a regular, array-like collection (of type [System.Collections.ObjectModel.Collection[psobject]) whose elements happen to be key-value pair objects.
As such, this output is enumerated in the pipeline.

Upvotes: 6

Related Questions