Created
June 5, 2018 15:04
-
-
Save eshess/1a972f542309943ac33e45101e746b23 to your computer and use it in GitHub Desktop.
Performing a left outer join using PowerShell LINQ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Initialize mock data to join | |
$Left = @() | |
$Right = @() | |
$ProductionStatusArray = @('In Production','Retired') | |
$PowerStatusArray = @('Online','Offline') | |
1..15 | Foreach-Object { | |
$Prop = @{ | |
Name = "Server$_" | |
PowerStatus = $PowerStatusArray[(Get-Random -Minimum 0 -Maximum 2)] | |
} | |
$Left += New-Object -Type PSObject -Property $Prop | |
} | |
1..10 | Foreach-Object { | |
$Prop = @{ | |
Name = "Server$_" | |
ProductionStatus = $ProductionStatusArray[(Get-Random -Minimum 0 -Maximum 2)] | |
} | |
$Right += New-Object -Type PSObject -Property $Prop | |
} | |
#In this instance both joins will be using the same property name so only one function is needed | |
[System.Func[System.Object, string]]$JoinFunction = { | |
param ($x) | |
$x.Name | |
} | |
#This is the delegate needed in GroupJoin() method invocations | |
[System.Func[System.Object, [Collections.Generic.IEnumerable[System.Object]], System.Object]]$query = { | |
param( | |
$LeftJoin, | |
$RightJoinEnum | |
) | |
$RightJoin = [System.Linq.Enumerable]::SingleOrDefault($RightJoinEnum) | |
New-Object -TypeName PSObject -Property @{ | |
Name = $LeftJoin.Name; | |
PowerStatus = $LeftJoin.PowerStatus; | |
ProductionStatus = $RightJoin.ProductionStatus | |
} | |
} | |
#And lastly we call GroupJoin() and enumerate with ToArray() | |
[System.Linq.Enumerable]::ToArray( | |
[System.Linq.Enumerable]::GroupJoin($Left, $Right, $JoinFunction, $JoinFunction, $query) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment