[英]Passing Hashes to a Powershell function problem
I must be missing something.我肯定错过了什么。 i have to variables: $var1 and $var2
我必须变量:$var1 和 $var2
$var1 | gm
TypeName: System.Collections.Hashtable
Each of them has IP and Port property, for example $var1[0].ip = '1.1.1.1';他们每个人都有 IP 和 Port 属性,例如 $var1[0].ip = '1.1.1.1'; $var1[0].ports = @(22,23,24)
$var1[0].ports = @(22,23,24)
Now I want to create a function that does some comparing between those 2 objects:现在我想创建一个 function 来比较这两个对象:
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: function 还没有准备好,我想知道的是为什么我在传递 $var1 和 $var2 时遇到问题我这样做:
CompareData ($var1, $var2)
and it looks like only $var1 is passing while $var2 comes empty, also, if i do (inside function):并且看起来只有 $var1 正在传递,而 $var2 为空,如果我这样做(内部函数):
$data1 | gm
System.Object[] System.Object[].ip
meaning the function isnt getting the variables as i want.意思是 function 没有得到我想要的变量。 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.当您使用括号时,PowerShell 会构造一个包含所有值的数组,并将其用作一个参数的值。
So, CompareData ($var1, $var2)
is equivalent to CompareData -data1 @($var1, $var2)
with no value specified for the -data2
parameter.因此,
CompareData ($var1, $var2)
等效于CompareData -data1 @($var1, $var2)
,没有为-data2
参数指定值。
If you use CompareData -data1 $var1 -data2 $var2
as suggested by @dwillits you should get the result you expect.如果您按照@dwillits 的建议使用
CompareData -data1 $var1 -data2 $var2
您应该得到您期望的结果。
I've had problems with my functions when calling them with parenthesis.用括号调用它们时,我的函数出现问题。 Have you tried calling your function like so?
你试过这样称呼你的 function 吗?
CompareData -data1 $var1 -data2 $var2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.