简体   繁体   中英

Display multiple array values in list in Powershell

I have multiple arrays like this:

$arrayList1 = @()
$arrayList2 = @()

$arrayList1 += "james"
$arrayList1 += "henry"
$arrayList1 += "bob"

$arrayList2 += "scott"
$arrayList2 += "john"
$arrayList2 += "meera"
$arrayList2 += "lisa"
$arrayList2 += "joseph"

And i want to display the output like this:

arrayList1 arrayList2
james scott
henry john
bob meera
lisa
joseph

Here is what i tried:

$output = @{}
$output.add('arrayList1',$arrayList)
$output.add('arrayList2',$arrayLis2)
[PSCustomObject]$output

$output

And the output looks like this:

arrayList2 arrayList1
{scott,john,meera,lisa,joseph} {james,henry,bob}

Note: The array won't have same number of data.

Any suggestions how i can get it in the order i want it?

Thanks

Sanjeev

A concise solution (note: assumes that at least one of the arrays is non-empty):

$arrayList1 = 'james', 'henry', 'bob'
$arrayList2 = 'scott', 'john', 'meera', 'lisa', 'joseph'

foreach ($i in 0..([Math]::Max($arrayList1.Count, $arrayList2.Count)-1)) {
  [pscustomobject] @{ arrayList1 = $arrayList1[$i]; arrayList2 = $arrayList2[$i] }
}

The above yields the following, as desired:

arrayList1 arrayList2
---------- ----------
james      scott
henry      john
bob        meera
           lisa
           joseph

Try something like this:

$Boys = "Bob", "Noah", "Liam"
$Girls = "Olivia", "Sophia", "Charlotte", "Emma"

Function Fix-Arrays {
    Param(
        [Parameter(Mandatory=$True)]
        [string[]]$ArrayNames,
        [switch]$NoWarnings = $False
    )
    $ValidArrays,$ItemCounts = @(),@()
    $VariableLookup = @{}
    
    ForEach ($Array in $ArrayNames) {
        Try {
            $VariableData = Get-Variable -Name $Array -ErrorAction Stop
            $VariableLookup[$Array] = $VariableData.Value
            $ValidArrays += $Array
            $ItemCounts += ($VariableData.Value | Measure).Count
        }

        Catch {
            If (!$NoWarnings) {Write-Warning -Message "No variable found for [$Array]"}
        }
    }

    $MaxItemCount = ($ItemCounts | Measure -Maximum).Maximum
    $FinalArray = @()
    
    For ($Inc = 0; $Inc -lt $MaxItemCount; $Inc++) {
        $FinalObj = New-Object PsObject
        ForEach ($Item in $ValidArrays) {
            $FinalObj | Add-Member -MemberType NoteProperty -Name $Item -Value $VariableLookup[$Item][$Inc]
        }

        $FinalArray += $FinalObj
    }

    $FinalArray
}

Fix-Arrays -ArrayNames "Boys","Girls"

Just edit Fix-Arrays (line 41) and the top two example arrays to suit your needs.

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