Simple PowerShell script to combine every item with every item


I needed a simple PowerShell code to generate hash tables with all possible pairs of a given array of strings. There are possibilities to use a similar method in .NET but I used only PowerShell functionality. This is my output:

$inputItems = 'aaa', 'bbb', 'ccc'
$pairItems = @()

$i = 0
foreach ($pairItemFirst in $inputItems)
{
    foreach ($pairItemSecond in ($inputItems | Where-Object -FilterScript { $_ -ne $pairItemFirst }))
    {
        $pairItems +=
        [ordered]@{
            PairNumber = $i
            First  = $pairItemFirst
            Second = $pairItemSecond
        }
    }
    $i++
}

$pairItems

Output:

Name       Value
----       -----
PairNumber 0
First      aaa
Second     bbb
PairNumber 0
First      aaa
Second     ccc
PairNumber 1
First      bbb
Second     aaa
PairNumber 1
First      bbb
Second     ccc
PairNumber 2
First      ccc
Second     aaa
PairNumber 2
First      ccc
Second     bbb

Leave a Reply

Your email address will not be published. Required fields are marked *

Active Directory Advanced function AlwaysOn Availability Groups AlwaysOn Failover Cluster Instances Building Cloud Cloud Cluster Cmdlet Database Deployment Design DFS Domain Controller DSC Fabric Failover Clustering File Server Group Policy Hardware Profile Host Hyper-V Installation Library Library Asset Library Server Network Operations Manager Orchestrator PowerShell PowerShell User Group PowerShell Workflow Security Service Manager SQL Server Storage System Center Template Time Time Synchronization Tips Virtual Machine Virtual Machine Manager VM Network VM Template Windows Server 2012 R2