簡體   English   中英

如何在Powershell中創建排列數組?

[英]How to create a permutation array in powershell?

我對排列有疑問。 例如,我有下表:

在此處輸入圖片說明

我想用此表進行排列。 第一列有兩個選項,第二列和第三列有三個選項。 輸出排列數組應如下所示:

在此處輸入圖片說明

有18個選項可將迭代安排在1-3列中。 問題是如何使用Powershell創建腳本來獲得這樣的數組? 以及如何將此數組輸出到Excel?

好的,從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()

您可以使用嵌套循環輕松地做到這一點:

$(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文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM