我有一个Powershell函数无法正常工作。应当将$ prm中给它的选择限制为最多5个。如果超过5个,它将提醒用户。如果在字符串中传递了0,则默认为null。

有人可以建议我需要做些什么来解决此问题:

Function GetListValues($prm, $charCount){

$buildStr="Call db.Fruit("

#no selection
if ($charCount -eq 0 ){
    $buildStr = $buildStr + "NULL,NULL,NULL,NULL,NULL);"
    write $buildStr
}elseif($charCount -ge 1 -and $charCount -le 4 ){

#selections made with then 5 parameter range

$arr = $prm.split(",");
if ($arr[0]) { $buildStr = $buildStr  + $arr[0] + "," } else { $buildStr = $buildStr + "Null," }
if ($arr[1]) { $buildStr  = $buildStr + $arr[1] + "," } else { $buildStr = $buildStr + "Null," }
if ($arr[2]) { $buildStr  = $buildStr + $arr[2] + "," } else { $buildStr = $buildStr + "Null," }
if ($arr[3]) { $buildStr  = $buildStr + $arr[3] + "," } else { $buildStr = $buildStr + "Null," }
if ($arr[4]) { $buildStr  = $buildStr + $arr[4] + ");" } else {$buildStr =  $buildStr + "Null);" }

write $buildStr


}else{
# too many selections

[System.Windows.MessageBox]::Show('Too many selections! A maximum of 5 only!')


}


}
$prm = "'Apple','Orange','Pear','Banana','Grapes'"
$charCount = ($prm.ToCharArray() | Where-Object {$_ -eq ','} | Measure-Object).Count
GetListValues $prm, $charCount

最佳答案

您的问题出在您的测试代码,而不是您的功能。对于powershell,您只能使用空格来分隔参数,而不能使用逗号。

因此,如果您将测试更改为
GetListValues $prm $charCount
然后代码起作用。

您可以忽略我之前的评论,因为我假设您将$ charCount值设置为元素数。但是仔细检查后,我发现您只是在计算逗号的数量,因此元素的数量将是#逗号+ 1(只要您有> 1个元素)

顺便说一句,$ charCount有点多余,因为Function可以自己解决这个问题,并使函数更具 flex ,因为它将消除调用代码传递不一致值的可能性。

08-17 14:59