使用两个Array PowerShell

时间:2017-11-09 00:13:51

标签: arrays powershell

我有两个数组:array1 [POP1,POP2,POP3 ...... POP30]和array2 [61,61,62 ... 61]。我需要创建一个值为62及其POP的新对象。

在这个例子中:

POP3 62。

我正在简化解释,因为我已经能够从数据库中获取值。

有人可以帮助我吗?

代码:

$target = @( )
$ini = 0 | foreach {
    $apiurl = "http://xxxxxxxxx:8080/fxxxxp/events_xxxx.xml"
    [xml]$ini = (New-Object System.Net.WebClient).downloadstring($apiurl)

    $target = $ini.events.event.name
    $nodename = $target

    $target = $ini.events.event.statuscode
    $statuscode = $target
}

$column1 = @($nodename)
$column2 = @($statuscode)

$i = 0
($column1,$column2)[0] | foreach {
    New-Object PSObject -Property @{
        POP    = $Column1[$i]
        Status = $column2[$i++]
    } | ft -AutoSize

2 个答案:

答案 0 :(得分:0)

假设你的意图是创建一个自定义对象数组,这些对象是由2个相同大小的数组的相应元素对构成的:

基于流水线的简洁解决方案(PSv3 +; for / foreach解决方案会更快):

$arr1 = 'one', 'two', 'three'
$arr2 = 1,     2,     3

0..$($arr1.Count-1) | % { [pscustomobject] @{ POP = $arr1[$_]; Status = $arr2[$_] } }

这会产生:

POP   Status
---   ------
one        1
two        2
three      3

答案 1 :(得分:0)

我真的无法弄清楚你想要做什么,但你肯定过于复杂了。以下是我对您的代码的看法:

# Here you have an empty array
$target = @( )

# Here you set call a Foreach, but you don't even need it
$ini = 0 | foreach {
    $apiurl = "http://xxxxxxxxx:8080/fxxxxp/events_xxxx.xml"
    [xml]$ini = (new-object System.Net.WebClient).downloadstring($apiurl)

    # You duplicated variables here. Just set $nodename = $ini.events.event.name
    $target = $ini.events.event.name
    $nodename = $target

    # You duplicate variables here. Just set $statuscode = $ini.events.event.name
    $target = $ini.events.event.statuscode
    $statuscode = $target
}

# You should already have arrays, so now you're making making more arrays duplicating variables again
$column1 = @($nodename)
$column2 = @($statuscode)

# counter, but you won't need it
$i = 0

# So here, youre making a new array again, but this contains two nested arrays. I don't get it. 
($column1,$column2)[0] | foreach {
    New-Object PSObject -Property @{
        POP    = $Column1[$i]
        Status = $column2[$i++]
    }  | ft -AutoSize
} # You were missing a closing bracket for your foreach loop

这是一个可能适合您的解决方案:

# Download the file
$apiurl = "http://xxxxxxxxx:8080/fxxxxp/events_xxxx.xml"
[xml]$ini = (New-Object System.Net.WebClient).DownloadString($apiurl)
# Set arrays
$nodename = $ini.events.event.name
$statuscode = $ini.events.event.statuscode

# Create $TableValues by looping through one array
$TableValues = foreach ( $node in $nodename )
{
    [pscustomobject] @{
        # The current node
        POP = $node
        # use the array method IndexOf
        # This should return the position of the current node
        # Then use that index to get the matching value of $statuscode
        Status = $statuscode[$nodename.IndexOf($node)]
    }    
}

# Add a custom value
$TableValues += [pscustomobject] @{
    POP = 'POP100'
    Status = 100
}

$TableValues | Format-Table -AutoSize