Skip to content

Instantly share code, notes, and snippets.

@TechDufus
Last active April 7, 2021 16:53
Show Gist options
  • Save TechDufus/ca9c7fde742e20b9c960619f2897f858 to your computer and use it in GitHub Desktop.
Save TechDufus/ca9c7fde742e20b9c960619f2897f858 to your computer and use it in GitHub Desktop.
Dynamically Generate Where-Object from [PSCustomObject] Values
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