bryane92
bryane92

Reputation: 59

using a HashTable for key with multiple values in Powershell

I am trying to figure out a way to have a key with multiple values that reads from a text file. I have it almost figured out but am stuck on how to make the key with the array values. I read it from a text file that is in the format of

Server1:
job1
job2
job3
Server2:
Job1
Server3:
Job1
Job2

I managed to split the lines, but cannot figure out how to make the key different and each have an array pair of jobs. My code is the following:

$hash = @{}
$content = Get-Content "C:\serversjobs.txt"
for ($i = 0; $i -lt $content.Count; $i++) {
    $line = $content[$i]
    if (($line -like '*:*') -and ($i + 1 -lt $content.Count)) {
        $nextLine = $content[$i+1]
        if ($nextLine -notlike '*:*') {
            $Server = $line.Replace(":", "").Trim().ToString()
            $hash.Server = @()
        }
    } elseif ($line -notlike '*:*') {
        $hash.Server += $line
    }
}
Write-Host $hash.Server

Whenever this outputs it just outputs all the jobs. I am not sure where to go from here. I am also looking ahead at the next line because some servers don't have any jobs, so they shouldnt be included. The for statement pretty much says if the next line also has ":" then this current line has no jobs attached to it so skip.

Upvotes: 1

Views: 762

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

You're making this way too complicated. Something like this should suffice:

$hash = @{}
Get-Content 'C:\serversjobs.txt' | ForEach-Object {
    $line = $_.Replace(':', '').Trim()
    if ($_ -like '*:*') {
        $server = $line
        $hash[$server] = @()
    } elseif ($line) {
        $hash[$server] += $line
    }
}

Upvotes: 1

Related Questions