Last active
April 7, 2021 16:53
-
-
Save TechDufus/ca9c7fde742e20b9c960619f2897f858 to your computer and use it in GitHub Desktop.
Dynamically Generate Where-Object from [PSCustomObject] Values
This file contains hidden or 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
Function Get-Example { | |
[CmdletBinding()] | |
param( | |
[parameter()] | |
[System.String] $FirstName, | |
[parameter()] | |
[System.String]$LastName | |
) | |
process { | |
return [PSCustomObject]@{ | |
FirstName = $FirstName | |
LastName = $LastName | |
} | |
} | |
} | |
Function Get-WhereObjectScriptBlock() { | |
[CmdletBinding()] | |
Param( | |
[Parameter()] | |
[System.String] $Operater = '-eq', | |
[Parameter()] | |
[System.String] $Joiner = '-AND', | |
[Parameter(Mandatory)] | |
[PSCustomObject] $InputObject | |
) | |
Process { | |
$WhereList = New-Object System.Collections.ArrayList | |
$Object | Get-Member -MemberType NoteProperty | Foreach-Object { | |
[void]$WhereList.Add("`$_.$($_.Name) $Operater '$($Object.($_.Name))'") | |
} | |
If ($WhereList.Count -gt 0) { | |
[scriptblock]::Create($WhereList -join " $Joiner ") | |
} | |
} | |
} | |
$Object = Get-Example -FirstName 'Stefan' -LastName 'Stranger' | |
$Where = Get-WhereObjectScriptBlock -InputObject $Object | |
If ($Null -ne $Where) { | |
$Object | Where-Object $Where | |
} Else { | |
$Object | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment