n8.
n8.

Reputation: 1738

Find key in hash table (ContainsKey) not working

I'm loading a hash table with this:

$htA = dir | Where-Object {$_.Name -match "\.output\.[A-Z]-[0-9]\.csv"} | select name,length

When I try to search the Key column like thusly:

$htA.ContainsKey($h.name)

I get this super neat-o error:

Method invocation failed because [Selected.System.IO.FileInfo] does not contain a method named 'ContainsKey'.

At line:3 char:9
 IF ($htA.ContainsKey($h.name) -eq $false) {

     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (ContainsKey:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound**

So is this not a legit hashtable?

Upvotes: 1

Views: 1652

Answers (1)

Gareth Lyons
Gareth Lyons

Reputation: 1972

$htA is created as the type cast to it, in this case System.IO.FileInfo. Try this:

$htA = @{} # Initialises as an empty hash table
foreach ($file in (dir | Where-Object {$_.Name -match "\.output\.[A-Z]-[0-9]\.csv"} | select name,length))
{
$htA.Add($file.name, $file.length) # Populate hash table
}

Upvotes: 2

Related Questions