0

I am having problems to group an array of objects by Environment. The following script show three environments with servers in each one. Now, I am trying to loop those objects by groups but getting errors with the Environment names. The following is my sample logic:

$array = @(("DEVELOPMENT", ("SRV1")), ("QA", ("SRV2", "SRV3")), ("PRODUCTION", ("SRV4", "SRV5")))

ForEach ($system in $array) {
    $envName = $array[0]
    ForEach ($hostname in $system[1]) {
        Write-Host ("Result for " + $hostname + " in " + $envName)
    }
}

The variable name $envName always returns the same wrong result.

[0]:"DEVELOPMENT"
[1]:"SRV1"

How can I group and loop $array[0] and $system[1] in the following way?

DEVELOPMENT = SRV1
QA          = SRV2, SRV3
PRODUCTION = SRV4, SRV5
2
  • 2
    Looks like a typo. Instead of $envName = $array[0] you should write $envName = $system[0]. Commented Jan 17, 2021 at 0:33
  • You are right - i have just realised it. Thanks Commented Jan 17, 2021 at 0:46

2 Answers 2

2

Another option would be to create an object array instead of an embedded string array.

class Server
{
    [string]$Environment
    [string]$ServerName
}


$Development = @("SRV1")
$Qa = @("SRV2", "SRV3")
$Production = @("SRV4", "SRV5")

$Array = @()

foreach ($System in $Development)
{
    $Server = [Server]::new()
    $Server.ServerName = $System
    $Server.Environment = "Development"
    $Array += $Server
}

foreach ($System in $Qa)
{
    $Server = [Server]::new()
    $Server.ServerName = $System
    $Server.Environment = "QA"
    $Array += $Server
}

foreach ($System in $Production)
{
    $Server = [Server]::new()
    $Server.ServerName = $System
    $Server.Environment = "Production"
    $Array += $Server
}

foreach ($System in $Array)
{
    Write-Host "Result for $($System.ServerName) in $($System.Environment)"
}
Sign up to request clarification or add additional context in comments.

Comments

0

The solution in the comments

"Instead of $envName = $array[0] you should write $envName = $system[0]"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.