如何在PowerShell中创建排列数组?

时间:2015-12-09 18:36:45

标签: arrays powershell permutation

我对排列有疑问。 例如,我有下表:

enter image description here

我想用这张表进行排列。第一列有两个选项,第二列和第三列有三个选项。输出排列数组应如下所示:

enter image description here

有18个选项可以在1-3列中排列iterms。问题是如何使用powershell创建脚本来获得这样的数组?以及如何将此数组输出到excel?

2 个答案:

答案 0 :(得分:3)

好的,从Joey的优秀答案中分离出来,要遍历具有已知列的数组,您可以执行以下操作(PowerShell v3或更高版本,可以在旧版本中完成,但会变得更复杂)。

#clean up any existing variables
Remove-Variable array, alliterations -ea 4

#create the sample array
[array]$array += [PSCustomObject]@{
    'Column 1' = 'Single load'
    'Column 2' = 'MAT1'
    'Column 3' = 'Country A'
}
[array]$array += [PSCustomObject]@{
    'Column 1' = 'Uniform distributed load'
    'Column 2' = 'MAT2'
    'Column 3' = 'Country B'
}
[array]$array += [PSCustomObject]@{
    'Column 1' = ''
    'Column 2' = 'MAT3'
    'Column 3' = 'Country C'
}

#Create all iterations from that array
ForEach($a in ($array.'Column 1'|Where{$_})){

    ForEach($b in ($array.'Column 2'|Where{$_})){

        ForEach($c in ($array.'Column 3'|Where{$_})){
            [array]$AllIterations += [PSCustomObject]@{
                'Column 1' = $a
                'Column 2' = $b
                'Column 3' = $c
            }
        }
    }
}

#Display results
$AllIterations

这将生成数组:

Column 1                 Column 2 Column 3 
--------                 -------- -------- 
Single load              MAT1     Country A
Single load              MAT1     Country B
Single load              MAT1     Country C
Single load              MAT2     Country A
Single load              MAT2     Country B
Single load              MAT2     Country C
Single load              MAT3     Country A
Single load              MAT3     Country B
Single load              MAT3     Country C
Uniform distributed load MAT1     Country A
Uniform distributed load MAT1     Country B
Uniform distributed load MAT1     Country C
Uniform distributed load MAT2     Country A
Uniform distributed load MAT2     Country B
Uniform distributed load MAT2     Country C
Uniform distributed load MAT3     Country A
Uniform distributed load MAT3     Country B
Uniform distributed load MAT3     Country C

要将其导入Excel,您可以像Joey建议的那样导出到CSV文件,也可以让PowerShell打开Excel并直接将数据粘贴到其中。

#Copy array to clipboard as a tab delimited CSV
$AllIterations | ConvertTo-CSV -Delimiter "`t" -NoTypeInfo | Select -Skip 1 | Clip

#Open Excel, create a blank workbook, and paste the data in at cell A1
$XL = New-Object -ComObject Excel.Application
$WB = $XL.Workbooks.Add()
$XL.Visible = $true
$XL.ActiveSheet.Cells.Item(1).PasteSpecial()

答案 1 :(得分:1)

您可以使用嵌套循环轻松完成此操作:

$(foreach ($a in 'Single Load','Uniform distributed load') {
  foreach ($b in 'MAT1','MAT2','MAT3') {
    foreach ($c in 'Country A','Country B','Country C') {
      New-Object -Prop @{Column1=$a;Column2=$b;Column3=$c}
    }
  }
}) | Export-Csv foo.csv -NoTypeInformation

然后可以通过Excel打开CSV文件。