Skip to content

Instantly share code, notes, and snippets.

@eshess
Created June 5, 2018 15:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eshess/1a972f542309943ac33e45101e746b23 to your computer and use it in GitHub Desktop.
Save eshess/1a972f542309943ac33e45101e746b23 to your computer and use it in GitHub Desktop.
Performing a left outer join using PowerShell LINQ
#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