Mike
Mike

Reputation: 21

Powershell multidimensional array IndexOf returning -1

I'm running a script that outputs a Citrix QFarm /load command into a text file; it's essentially two columns that I then input into a multidimensional array, such that it looks like:

SERVER1 100
SERVER2 200
SERVER3 300

I'm looking to find the indexOf a particular server so I can then check what the loadbalancer level is. When I use the indexOf method, I'm only ever getting a return of -1; but the explicity write-host at the end of the script shows that the answer should come back as 41.

Is there some magic that needs to occur in order to use IndexOf with a 2d array?

$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!"
}

Running this gives the output:

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

Upvotes: 2

Views: 4072

Answers (1)

Tomas Panik
Tomas Panik

Reputation: 4609

I assume that in your case it would work only if both columns would match (hostname|level) like: [array]::IndexOf($arrQFarm, ($strHostName , $strLB)). According to IndexOf it compares whole item of the array (which is in your case also array)

maybe I won't answer the question directly but what about to use Hashtable (thanks to dugas for correction)? 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])
}

Upvotes: 1

Related Questions