0

Need advice on loop $Variable contains 11111 22222

foreach ($variable in $value) {
             for ([byte]$c = [char]'b'; $c -le [char]'c'; $c++) {
                    $variable."([char]$c)" } }

I am looking output as 11111b and then 22222c but currently, I am getting 11111b , 11111c and then 22222b and then 22222c. Kindly advice

gary
  • 157
  • 1
  • 3
  • 15
  • What is the purpose of this? Is it for a homework assignment? – Bill_Stewart Sep 30 '17 at 20:49
  • Yes, it's a home assignment !!! – gary Sep 30 '17 at 20:58
  • You really should ask your instructor for help. Getting someone to do your work for you might be considered cheating. – Bill_Stewart Sep 30 '17 at 20:59
  • It's like my office assignment and it's a small part of it ... – gary Sep 30 '17 at 21:01
  • @Bill_Stewart do I need to use break; after first loop end? – gary Sep 30 '17 at 21:11
  • Thanks I have updated the question ... It's very confusing as how to add alphabets in series to the variable values.I am unable to find any example on net ..:( – gary Sep 30 '17 at 21:55
  • It's the same problem as described here https://stackoverflow.com/questions/25191803/powershell-cli-foreach-loop-with-multiple-arrays - stepping through two collections (values and characters) at the same time, pairing them up. – TessellatingHeckler Sep 30 '17 at 22:15

1 Answers1

1

I am assuming you mean that $value, not $variable, contains 11111 and 22222, specifically in an array.

Since you want $c to maintain its value between iterations of the foreach loop you need to initialize $c outside of the foreach loop. Therefore, you really don't need (or, rather, should not use) two loops at all.

$value = 11111, 22222;
[Byte] $c = [Char] 'b';

foreach ($variable in $value)
{
    "$variable$([Char] $c++)"
}

This gives the output you are seeking:

11111b
22222c
Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68