1
votes

Do I need to redefine Objects in Functions?

I have following main.ps1

$MyDict = New-Object 'system.collections.generic.dictionary[string,string]' 
loadDict([ref]$MyDict)

and I have a functions.psm1 with the function

function loadDict([ref]$return)
{
    #pseudo - load data from table
    foreach ($TableRow in $LoadTable){
        if($return.ContainsKey($TableRow.KEYID) -eq $false){
            $return.Add($TableRow.KEYID, $TableRow.TEXT.Trim())
        }
    }
}

but I get the following Error..

[System.Management.Automation.PSReference'1[[System.Collections.Generic.Dictionary'2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]] "ContainsKey" Method not found

When I do not call the Function, but use the Function Code in Main, there is no Problem.

(corrected "[" typo)

2

2 Answers

0
votes

The answer is no. You don't need to redefine the objects.

Like Esperento57 mentioned, you have a [ within your if condition. Anyhow, you may consider to use a bultin hashtable:

function loadDict
{
    Param
    (
        [hashtable]$MyDict
    )
    #pseudo - load data from table
    foreach ($TableRow in $LoadTable)
    {
        if($MyDict.ContainsKey($TableRow.KEYID) -eq $false)
        {
            $MyDict.Add($TableRow.KEYID, $TableRow.TEXT.Trim())
        }
    }
}

$MyDict = @{}
loadDict([ref]$MyDict)
0
votes

remove ref into your parameter and put the type like this :

function loadDict([system.collections.generic.dictionary[string,string]]$return)
{
    #pseudo - load data from table
    foreach ($TableRow in $LoadTable){
        if($return.ContainsKey($TableRow.KEYID) -eq $false){
            $return.Add($TableRow.KEYID, $TableRow.TEXT.Trim())
        }
    }
}

$MyDict = New-Object 'system.collections.generic.dictionary[string,string]' 
loadDict($MyDict)