Aslı
Aslı

Reputation: 115

How to remove duplicated elements on hashtable that were added with foreach in powershell script?

I have an array which has duplicated elements. I wish to use a dictionary for removing the duplicated elements. This is my code block :

$dictionary = [ordered]@{}
ForEach ($item In $pkg){
    $dictionary.Add($item.Id, $item.Version)
}

The dictionary still has duplicated elements, but when adding to it like this:

$dictionary.Add("NHibernate", "4.0.4.4000")

$dictionary.Add("NHibernate", "4.0.4.4000")

it is not allowed. What am I doing wrong?

The array is a result of doing this

@( Get-Project -All | ? { $_.ProjectName } | % { Get-Package -ProjectName $_.ProjectName } ) | ? { $_.LicenseUrl } | ...

in the package manager console in Visual Studio.

Upvotes: 0

Views: 829

Answers (2)

Theo
Theo

Reputation: 61123

If you want to allow identical keys to overwrite the value already in the dictionary (last item 'wins'), use this syntax:

foreach ($item In $pkg){
    $dictionary[$item.Id] = $item.Version
}

If you want to skip items with the same keys, use this:

foreach ($item In $pkg) {
    if (!($dictionary.Contains($item.Id))) {
        $dictionary.Add($item.Id, $item.Version)
    }
}

Upvotes: 1

TobyU
TobyU

Reputation: 3918

If you don't want to overwrite your values of already existing keys, you could check if the key already exists before adding it to the hashtable (again):

ForEach ($item In $pkg){
    if( -not $dictionary.Item($item.Id)){
        $dictionary.Add($item.Id, $item.Version)
    }
}

Upvotes: 0

Related Questions