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
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
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)'"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With