2

still very inexperienced in Powershell, but as is well known, every journey begins with the first steps.

I define two arrays in the script:

$array1 = @("server1", "server2")
$array2 = @("SID1", "SID2")

The SID1 and server1 belong together.

I then want to combine the two arrays using a loop: Example:

foreach ($i in $array1) {
Write-Host "Server = ${i}"
}

How can I combine the two arrays? Ideal is: ...

Write-Host "Server=${i}" and SID=${?}"

...

Can the two arrays be built into the foreach so that both values are filled when executing on the write host?

Thanks for your ideas and help.

Many greetings

Carlos

1

4 Answers 4

4

An alternative approach is to use [System.Linq.Enumerable]::Zip which provides convenient API(like python zip function). ie, You could do

$array1 = @("server1", "server2")
$array2 = @("SID1", "SID2")


$doSomethingWithPair = {
    param($a, $b)

    Write-Output "I have $a and $b"
}

[System.Linq.Enumerable]::Zip(
  $array1, 
  $array2, 
  [Func[Object, Object, Object]]$doSomethingWithPair
)

This will print

I have server1 and SID1
I have server2 and SID2
Sign up to request clarification or add additional context in comments.

Comments

2

Use a for loop to generate a range of valid indices for each array:

for($i = 0; $i -lt $array1.Count; $i++){
    Write-Host "Server named '$($array1[$i])' has SID '$($array2[$i])'"
}

But a better solution would be to create a single array of objects that have both pieces of information stored in named properties:

$array = @'
Name,ID
Server1,SID1
Server2,SID2
'@ |ConvertFrom-Csv

Now you can use a foreach loop without having to worry about the index:

foreach($computer in $array){
    Write-Host "Server named '$($computer.Name)' has SID '$($computer.ID)'"
}

Comments

2

You could use a hash table or ordered dictionary (if you need the keys to keep their order), might be a good approach for your need.

  • Hash Table
$hash = @{
    server1 = "SID1"
    server2 = "SID2"
}
  • Ordered Dictionary
$dict = [ordered]@{
    server1 = "SID1"
    server2 = "SID2"
}

Then you can iterate over the key / value pairs either using .GetEnumerator():

foreach($pair in $hash.GetEnumerator()) {
    Write-Host ("Server={0} and SID={1}" -f $pair.Key, $pair.Value)
}

Or by it's .Keys property:

foreach($key in $hash.PSBase.Keys) {
    Write-Host ("Server={0} and SID={1}" -f $key, $hash[$key])
}

Comments

0
$array1 = @("server1", "server2")
$array2 = @("SID1", "SID2")

for($i=0; $i -lt $array1.Count; $i++){
Write-Host $array1[$i] ":"$array2[$i]

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.