Search code examples
arrayspowershellpowershell-2.0powershell-4.0

Two array iteration


I'm very new to PowerShell and learning how to do stuff. I have two very big arrays with same number of objects. How to iterate both arrays at same time.

Example:

$first = @(
    'First'
    'Second'
    ...
)
$second = @(
    'one'
    'two'
    ...
)

I need to pair objects and print it like this:

First one
Second two

I try using foreach, but I can't figure out how. I also try "for" loop, but always getting print mess up.

Some code example help will be very much appreciated. Thank you in advance.

UPDATE: Here is code I was using

$All = @( '1.1.1.1/80' '2.2.2.2/443' '3.3.3.3/8883' )
$AllProtocols = @( 'HTTP' 'HTTPS' 'TCP' )

$All | ForEach-Object -Begin $null -Process {

    $Ip = $_.Split("/")[0]
    $Port = $_.Split("/")[1]

    $AllProtocols | ForEach-Object -Begin $null -Process {
        $Protocol = $_

        $Test = New-Object PSObject -Property @{
            RemoteAddress = $Ip
            LocalPort = $Port
            Protocol = $Protocol
        }    

        $Ip
        $Port
        $Protocol
        Write-Host "RemoteAddress $($Test.RemoteAddress) LocalPort $($Test.LocalPort) Protocol $($Test.Protocol)" 

    } -End $null

} -End $null

Solution

  • First of all, the arrays you define are missing commas between the different values.
    The way you have coded with spaces in between is wrong (the editor should have showed you that).

    Also, when you have more that one value to declare, there is no need for the @() construct.

    Then, you are making this a lot harder than it should. Why not use a simple counter loop to iterate the arrays on index?

    $All = '1.1.1.1/80','2.2.2.2/443','3.3.3.3/8883'
    $AllProtocols = 'HTTP', 'HTTPS', 'TCP'
    
    for ($i = 0; $i -lt $All.Count; $i++) { 
        $ip, $port = $All[$i] -split '/'
    
        [PsCustomObject]@{
            RemoteAddress = $ip
            LocalPort     = $port
            Protocol      = $AllProtocols[$i]
        }
    }
    

    Result:

    RemoteAddress LocalPort Protocol
    ------------- --------- --------
    1.1.1.1       80        HTTP    
    2.2.2.2       443       HTTPS   
    3.3.3.3       8883      TCP
    

    Of course, this only outputs to the console, but if you capture the result from the loop in a variable like with $result = for ($i = 0; $i -lt $All.Count; $i++) { .. }, you can save it to CSV file as bonus for instance.