2013-03-19 113 views
2

我正在运行一个脚本,它将Citrix QFarm/load命令输出到文本文件中;它本质上是两列,我再输入到一个多维数组,这样它看起来像:Powershell多维数组IndexOf返回-1

SERVER1 100 
SERVER2 200 
SERVER3 300 

我期待找到的indexOf一个特定的服务器,所以我可以再检查负载均衡器级别是什么。当我使用indexOf方法时,我只得到-1的返回值;但脚本末尾的显式写主机显示答案应该会回到41.

是否需要发生某些魔法才能将IndexOf与2d数组一起使用?

$arrQFarm= @() 
$reader = [System.IO.File]::OpenText("B:\WorkWith.log") 
try { 
for(;;) { 
    $str1 = $reader.ReadLine() 
    if ($str1 -eq $null) { break } 

    $strHostname = $str1.SubString(0,21) 
    $strHostname = $strHostname.TrimEnd() 
    $strLB = $str1.SubString(22) 
    $strLB = $strLB.TrimEnd() 

    $arrQFarm += , ($strHostName , $strLB) 
    } 
} 
finally { 
$reader.Close() 
} 

$arrCheckProdAppServers = "CTXPRODAPP1","CTXPRODAPP2" 


foreach ($lines in $arrCheckProdAppServers){ 
$index = [array]::IndexOf($arrQFarm, $lines) 
Write-host "Index is" $index 
Write-Host "Lines is" $lines 

} 

if ($arrQFarm[41][0] -eq "CTXPRODAPP1"){ 
Write-Host "YES!" 
} 

运行这给输出:

PS B:\Citrix Health Monitoring\249PM.ps1 
Index is -1 
Lines is CTXPRODAPP1 
Index is -1 
Lines is CTXPRODAPP2 
YES! 
+0

IndexOf不支持多维数组。在你的例子中,你看起来像你正在尝试使用关联数组。看看使用Hashtable,以服务器为关键,负载平衡器为值:http://technet.microsoft.com/en-us/library/ee692803.aspx – dugas 2013-03-19 20:16:26

回答

1

我认为在你的情况下,它会工作只有两列将匹配(主机名|级别),如:[array]::IndexOf($arrQFarm, ($strHostName , $strLB))。根据IndexOf它比较整个项目的阵列(这是你的情况也阵列)

也许我不会直接回答这个问题,但怎么使用Hashtable(感谢dugas纠正)? like:

$arrQFarm= @{} 
$content = Get-Content "B:\WorkWith.log" 
foreach ($line in $content) 
{ 
    if ($line -match "(?<hostname>.+)\s(?<level>\d+)") 
    { 
     $arrQFarm.Add($matches["hostname"], $matches["level"]) 
    } 
} 

$arrCheckProdAppServers = "CTXPRODAPP1","CTXPRODAPP2" 

foreach ($lines in $arrCheckProdAppServers) 
{ 
    Write-host ("Loadbalancer level is: {0}" -f $arrQFarm[$lines]) 
} 
+0

在你的例子中,你使用了一个Hashtable,而不是一本字典。 – dugas 2013-03-19 20:15:28

+0

确实如此,感谢您的纠正 – 2013-03-19 20:37:53