简体   繁体   中英

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>"}
    }
}

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.

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>"
    }  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM