PowerShell多维数组中的引用元素

时间:2015-05-11 12:56:31

标签: arrays powershell multidimensional-array

我有CSV文件

enter image description here

我的PowerShell脚本尝试在多维数组中存储SourceIP,DestinationIP和Traffic

$source = @((Import-Csv D:\Script\my.csv).SourceIP)
$dest = @((Import-Csv D:\Script\my.csv).DestinationIP)
$t = @((Import-Csv D:\Script\my.csv).Traffic)

$multi = @($source),@($dest),@($t)

当我尝试从$ multi的第一个元素读取时,我希望得到一个SourceIP列表

foreach ($q in $multi){
    write-host $q[0]
    write-host `n
}

但相反,我得到了SourceIP,DestinationIP,Traffic,即

10.153.128.110


10.251.68.80


3.66 GB

如果我尝试

foreach ($q in $multi){
    write-host $q[0][0][0]
    write-host `n

}

我得到了

1


1


3

如何解决问题?

更新

最终目标是

  1. 计算总流量
  2. 如果SourceIP或目标IP符合特定模式(即10.251.22.x
  3. ),则计算流量
  4. 获取百分比
  5. 更新II

    我能够获取导入CSV和仅计算总带宽的代码,但我还需要具有特定模式的SourceIP和DestinationIP的带宽。

    $t = @((Import-Csv D:\Script\my.csv).Traffic)
    
    foreach ($k in $t){
        write-host $k
    
    }
    
    
    foreach ($i in $t){
        $j += ,@($i.split(" "))
    }
    
    
    
    foreach ($m in $j){
        switch ($m[1]){
            GB {
                $m[0] = [int]($m[0]) * 1000
                $m[1] = 'MB'
            }
            MB {}
            KB {
                $m[0] = [int]($m[0]) / 1000
                $m[1] = 'MB'
            }
        }
        $total_bandwidth += $m[0]
    }
    
    write-host Total bandwidth is ("{0:N2}" -f $total_bandwidth) MB 
    

2 个答案:

答案 0 :(得分:2)

您不应将对象数组拆分为多个并行属性数组。当物体是完整的时,它很容易操作。

$Scale=@{
     B=1e00
    KB=1e03
    MB=1e06
    GB=1e09
    TB=1e12
}
$TrafficBytes={
    $a=-split$_.Traffic
    [double]$a[0]*$Scale[$a[1]]
}

Import-Csv D:\Script\my.csv|
ForEach-Object $TrafficBytes|
Measure-Object -Sum #total traffic

Import-Csv D:\Script\my.csv|
Where-Object {$_.DestinationIP-like'10.*'}| #condition
ForEach-Object $TrafficBytes|
Measure-Object -Sum #traffic by condition

答案 1 :(得分:1)

PetSerAl对转换有一个好主意,但是这是一种方法,需要只迭代一次CSV并给出你的百分比。

$filter = "10.251.22.*"

$Scale=@{
     B=1e00
    KB=1e03
    MB=1e06
    GB=1e09
    TB=1e12
}


$myCsv = Import-Csv D:\Script\my.csv | Select-Object *, @{ Name = "TrafficBytes"; Expression = { $a = -split $_.Traffic; [double] $a[0] * $Scale[$a[1]] } }
$trafficFiltered = $myCsv | Group-Object { $_.SourceIP -like $filter -or $_.DestinationIP -like $filter } | Select-Object @{ Name = "IPFilter"; Expression = { if ($_.Name -eq $true) { $filter } else { "Other" } } }, @{ Name = "TrafficBytes"; Expression = { ($_.Group | Measure-Object -Sum "TrafficBytes").Sum } }
$trafficTotal = $myCsv | Measure-Object -Sum TrafficBytes
$trafficReport = Select-Object IPFilter, TrafficBytes, @{ Name = "Percent"; Expression = { "{0:P}" -f $_.TrafficBytes / $trafficTotal.Sum * 100.0 } }

$trafficReport