简体   繁体   中英

Returning relevant value from another array in PowerShell

I have two arrays filled with strings that are relational. I need to pull back the value from array 2 whilst iterating through array 1 in a foreach loop. How your i Achieve this? Here is my code:

$contracts = @("xytt"
               "deff"
               "mnoo")

$labels = @("London contract"
            "Dubai contract"
            "Glasgow contract")

foreach ($contract in $contracts){
#Do stuff with $contract
#Return label associated to contract object
}

You could use for loop and an index variable instead of foreach :

for ($i=0; $i -lt $contracts.Length; $i++) {
    $contract = $contracts[$i]
    $label = $labels[$i]
    Write-Host "$contract : $label"
}

I agree with EBGreen, a hash table is more suited to the task.

Similarly to Janne Tuukkanen's script this one uses an index,
but based on a normal ForEach.

ForEach ($contract in $contracts){
    "{0} - {1}" -f $contract, $labels[$contracts.IndexOf($contract)]
}

Sample output:

xytt - London contract
deff - Dubai contract
mnoo - Glasgow contract

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