5

Is it possible to pull two variables into a Foreach loop?

The following is coded for the PowerShell ASP. The syntax is incorrect on my Foreach loop, but you should be able to decipher the logic I'm attempting to make.

$list = Get-QADUser $userid -includeAllProperties | Select-Object -expandproperty name
$userList = Get-QADUser $userid -includeAllProperties | Select-Object -expandproperty LogonName
if ($list.Count -ge 2)
{
    Write-host "Please select the appropriate user.<br>"
    Foreach ($a in $list & $b in $userList)
    {
        Write-host "<a href=default.ps1x?UserID=$b&domain=$domain>$b - $a</a><br>"}
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
gp80586
  • 169
  • 2
  • 4
  • 13

2 Answers2

14

Christian's answer is what you should do in your situation. There is no need to get the two lists. Remember one thing in PowerShell - operate with the objects till the last step. Don't try to get their properties, etc. until the point where you actually use them.

But, for the general case, when you do have two lists and want to have a Foreach over the two:

You can either do what the Foreach does yourself:

$a = 1, 2, 3
$b = "one", "two", "three"

$ae = $a.getenumerator()
$be = $b.getenumerator()

while ($ae.MoveNext() -and $be.MoveNext()) {
    Write-Host $ae.current $be.current
}

Or use a normal for loop with $a.length, etc.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
manojlds
  • 290,304
  • 63
  • 469
  • 417
6

Try like the following. You don't need two variables at all:

$list = Get-QADUser $userid -includeAllProperties 
if ($list.Count -ge 2)
{
    Write-Host "Please select the appropriate user.<br>"
    Foreach ($a in $list)
    {
        Write-Host "<a href=default.ps1x?UserID=$a.LogonName&domain=$domain>$a.logonname - $a.name</a><br>"
    }  
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CB.
  • 58,865
  • 9
  • 159
  • 159