简体   繁体   中英

Passing Hashes to a Powershell function problem

I must be missing something. i have to variables: $var1 and $var2

$var1 | gm 
 TypeName: System.Collections.Hashtable

Each of them has IP and Port property, for example $var1[0].ip = '1.1.1.1'; $var1[0].ports = @(22,23,24)

Now I want to create a function that does some comparing between those 2 objects:

Function CompareData ($data1,$data2){
    $data1 | gm #this is just for me to test whats wrong
    write-host "first data $data1.ip" #just for me
    write-host "Second data $data2.ip" #just for me
    $str =''
    #check each ip in data2 if it exists in data1
    #if it exists, start checking for ports
    #if not exists do bla bla
    For ($i=0; $i -lt $data2.count; $i++){
        $ip = $data2[$i].ip
        for ($j=0; $j -lt $data1.count; $j++){
            if ($data1[$j].ip -eq $ip){
                $str += "$ip`r`n"
                $str += "Base ports: $data1[$i].ports`r`n"
                $str += "Current ports: $data2[$j].ports`r`n"
            }
        }
    }
}

the function isnt ready, what i do want to know is why im having a problem passing $var1 and $var2 Im doing this:

CompareData ($var1, $var2)

and it looks like only $var1 is passing while $var2 comes empty, also, if i do (inside function):

$data1 | gm
System.Object[] System.Object[].ip

meaning the function isnt getting the variables as i want. what am i missing here?

When you use parentheses, PowerShell constructs an array with all the values in it, and uses that as the value for one parameter.

So, CompareData ($var1, $var2) is equivalent to CompareData -data1 @($var1, $var2) with no value specified for the -data2 parameter.

If you use CompareData -data1 $var1 -data2 $var2 as suggested by @dwillits you should get the result you expect.

I've had problems with my functions when calling them with parenthesis. Have you tried calling your function like so?

    CompareData -data1 $var1 -data2 $var2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM