0

I have 2 arrays here one contains the servername and other contains the IP.

I need to loop through them and create a key value pair like below for each server

server1:ip1
server2:ip2

I have written below code, but the problem is if i debug the code using F11, it is working fine, but i don't it gives some error which is different every time.

so feeling like it is not that reliable piece to continue.

    $NewDNSEntryName = $DNSEntryName.Split(",")
    $DNSIPs = $DNSIP.Split(",")


if($DNSEntryName -match "," -or $DNSIP -match ",")
    {   

   0..($NewDNSEntryName.Count - 1) | ForEach-Object {

   $fullName=""
   $fullName += @("$($NewDNSEntryName[$_]):$($DNSIPs[$_])")

This is the line where i am facing trouble

0..($NewDNSEntryName.Count - 1) | ForEach-Object

Please let me know why this code is behaving like this else any alternate idea is appreciated

3
  • Can you update your question with some specific issues/errors you are getting? Commented Aug 13, 2019 at 15:53
  • Does each list align exactly? If so, you can use a standard for loop and access the same index among each list. So $NewDNSEntryName[0] and $DNSIPs[0] would correspond. Commented Aug 13, 2019 at 15:54
  • There is no error. what it does it directly comes out of the loop without executing anything. Commented Aug 13, 2019 at 15:56

1 Answer 1

3

Assuming each item in each list corresponds with each other exactly, you can use a for loop and loop through the array indexes.

$NewDNSEntryName = $DNSEntryName.Split(",")
$DNSIPs = $DNSIP.Split(",")

for ($i = 0; $i -lt $DNSIPs.count; $i++) {
    "{0}:{1}" -f $NewDNSEntryName[$i],$DNSIPs[$i]
}

For the code above to work, $DNSEntryName and $DNSIP must be single strings with commas between names and IPs. If $DNSEntryName and $DNSIP are already lists or arrays, something else will need to be done.

In your attempt, technically, your logic should work given everything written above is true. However, $fullName is emptied at every single iteration, which may produce undesirable results.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @AdminOfThings

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.