Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple variables in Foreach loop [PowerShell]

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>"}
    }
}
like image 273
gp80586 Avatar asked Oct 17 '11 15:10

gp80586


2 Answers

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.

like image 124
manojlds Avatar answered Nov 15 '22 05:11

manojlds


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>"
    }  
}
like image 36
CB. Avatar answered Nov 15 '22 06:11

CB.