Skip to content

Instantly share code, notes, and snippets.

@letmaik
Created April 27, 2017 09:23
Show Gist options
  • Save letmaik/d650ee257a27df8eac0f71f17aa99765 to your computer and use it in GitHub Desktop.
Save letmaik/d650ee257a27df8eac0f71f17aa99765 to your computer and use it in GitHub Desktop.
Cartesian product with keys (cross join) in PowerShell
function CartesianProduct {
param
(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Hashtable]
$values = @{ Foo = 1..5; Bar = 1..10}
)
$keys = @($values.GetEnumerator() | ForEach-Object { $_.Name })
$result = @($values[$keys[0]] | ForEach-Object { @{ $keys[0] = $_ } })
if ($keys.Length -gt 1) {
foreach ($key in $keys[1..($keys.Length - 1)]) {
$result = foreach ($entry in $result) {
foreach ($value in $values[$key]) {
$entry + @{ $key = $value }
}
}
}
}
$result
}
foreach ($entry in CartesianProduct @{ Foo = 0..3; Bar = ("a", "b") }) {
Write-Host "Foo = $($entry.Foo) Bar = $($entry.Bar)"
}
<#
Foo = 0 Bar = a
Foo = 1 Bar = a
Foo = 2 Bar = a
Foo = 3 Bar = a
Foo = 0 Bar = b
Foo = 1 Bar = b
Foo = 2 Bar = b
Foo = 3 Bar = b
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment