Powershell多维数组IndexOf返回-1

时间:2013-03-19 19:44:08

标签: windows powershell

我正在运行一个脚本,将Citrix QFarm / load命令输出到文本文件中;它基本上是两列,然后我输入到一个多维数组中,它看起来像:

SERVER1 100
SERVER2 200
SERVER3 300

我正在寻找索引特定服务器,以便我可以检查负载均衡器级别是什么。当我使用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!

1 个答案:

答案 0 :(得分:1)

我假设在你的情况下,只有当两个列匹配(主机名|级别)时才会起作用:[array]::IndexOf($arrQFarm, ($strHostName , $strLB))。根据{{​​3}},它比较了数组的整个项目(在你的情况下也是数组)

也许我不会直接回答这个问题但是如何使用Hashtable(感谢dugas进行更正)? 像:

$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])
}