Skip to content

Instantly share code, notes, and snippets.

@mutaguchi
Created May 30, 2023 09:59
Show Gist options
  • Save mutaguchi/f72f5e0376be0b876b44493b06a40be0 to your computer and use it in GitHub Desktop.
Save mutaguchi/f72f5e0376be0b876b44493b06a40be0 to your computer and use it in GitHub Desktop.
Test-All, Test-Any
function Test-All
{
[CmdletBinding()]
param(
[scriptblock]
$Predicate,
[Parameter(ValueFromPipeline)]
[PSObject]
$InputObject
)
begin
{
$all = $true
}
process
{
if ($all -and -not (& $Predicate $InputObject))
{
$all = $false
}
}
end
{
$all
}
}
function Test-Any
{
[CmdletBinding()]
param(
[scriptblock]
$Predicate,
[Parameter(ValueFromPipeline)]
[PSObject]
$InputObject
)
begin
{
$any = $false
}
process
{
if (-not $any -and (& $Predicate $InputObject))
{
$any = $true
}
}
end
{
$any
}
}
@(1, 1, 1) | Test-All { $_ -eq 1 } # True
@(1, 2, 3) | Test-All { $_ -eq 1 } # False
@() | Test-All { $_ -eq 1 } # True
@(1, 1, 1) | Test-Any { $_ -eq 1 } # True
@(1, 2, 3) | Test-Any { $_ -eq 1 } # True
@() | Test-Any { $_ -eq 1 } # False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment