0

So say I have 2 arrays.

$Letters = ("A","B","C")
$Numbers = ("1","2","3")

How would you construct a foreach loop such that this worked:

foreach ($letter in $letters) {set-something $number} where I could do a pair of values such that

A was set to 1, B was set to 2, C was set to 3, and so on. What is this even called? I thought it was called nested loops, but searching all over and it seems like that is NOT what this is called. Many thanks!

1
  • This is called Ziping the two lists. Not sure of the exact syntax to do it in powershell. Commented Nov 13, 2013 at 20:45

1 Answer 1

4

If it is a Zip op then this will do the trick:

C:\PS> $Letters | Foreach {$i=0} {@($_,$Numbers[$i++]}
A
1
B
2
C
3

But I think you might want this:

C:\PS> $Letters | Foreach {$i=0;$ht=@{}} {$ht."$_"=$Numbers[$i++]}
C:\PS> $ht.A
1
C:\PS> $ht.B
2
C:\PS> $ht.C
3
Sign up to request clarification or add additional context in comments.

3 Comments

That seems to work, however how to I capture the "Value" and use it in a command? For example say I wanted to write-host "$Letters = $Numbers"
Thank you! I'm guessing $ht stands for hash table? I'm trying to learn this language from zero scripting beyond batch/shell scripting. I've been tasked to develop build scripts for our IIS web servers pulling all the data from an external config database. :)
Yes, $ht is just a variable name but I tend to use it for temp hashtables.

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.