Skip to content

Instantly share code, notes, and snippets.

@sean-m
Last active July 20, 2021 00:01
Show Gist options
  • Save sean-m/3143bbdd60e18aa9b28e27168e96705e to your computer and use it in GitHub Desktop.
Save sean-m/3143bbdd60e18aa9b28e27168e96705e to your computer and use it in GitHub Desktop.
Simple rule matcher for PowerShell. Allows writing logic as a class that will match any or all of the predicates and optionally return a value on match.
class IRule {
[System.Collections.Generic.IEnumerable[IRule]]$Rules
# Or, Any : bail on first match
# And, All : evaluate all rules, only return a result if they all succeed
[ValidateSet("Or","Any", "And", "All")]
$MatchType
# Called on matching rules, overload in an inherited class to return
# values relevant to that rule.
[object] OnMatch ($input) { return $null }
# Execute matches on the collection of rules or overload in an
# inherited class to define the rule predicate.
[object[]] Matches ($input) {
switch ($this.MatchType) {
{ 'Or' -or 'Any' } {
$match = $this.Rules.Where({ $_.Matches($input) }, 'First')
if ($match) {
return $match.OnMatch($input)
}
return $null
}
{ 'And' -or 'All' } {
$match, $else = $this.Rules.Where({ $_.Matches($input) -eq $true }, 'Split')
if ($match -and -not $else) {
$results = $match | foreach { $_.OnMatch($input) }
if (-not $results) { return $true }
return $results
}
}
}
return $null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment