Multiple variables in Foreach loop [PowerShell]

雨燕双飞 提交于 2019-12-07 05:05:53

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/7796363/multiple-variables-in-foreach-loop-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!