Skip to content

Instantly share code, notes, and snippets.

@PanosGreg
Last active November 28, 2022 22:13
Show Gist options
  • Save PanosGreg/8df08e598d12f26126dfe4b85523c76b to your computer and use it in GitHub Desktop.
Save PanosGreg/8df08e598d12f26126dfe4b85523c76b to your computer and use it in GitHub Desktop.
function Test-TrueForAll {
<#
.SYNOPSIS
Checks if all items in an array have the same value
.EXAMPLE
'a','a','b' | Test-TrueForAll -ShouldBe 'a'
# returns False
.EXAMPLE
$false,$false,$false | Test-TrueForAll -ShouldBe $false
# returns True
.EXAMPLE
$ver1 = [version]'1.1' ; $ver2 = [version]'2.1'
$ver1,$ver2,$ver1 | Test-TrueForAll -ShouldBe $ver1
# returns False
.EXAMPLE
$result1 = 'a' -eq 'a'
$result2 = 'b' -eq 'b'
$result3 = 'c' -eq 'c'
$result1,$result2,$result3 | Test-TrueForAll
# returns True
#>
[OutputType([bool])]
[CmdletBinding()]
param (
[Parameter(Position=0)]$ShouldBe = $true,
[Parameter(ValueFromPipeline=$true,Position=1)]$InputArray
)
Begin {
$All = [System.Collections.Generic.List[Object]]::new()
}
Process {
$InputArray | foreach {$All.Add($_)}
}
End {
if ($All.Count -eq 0 -or $All.Contains($null)) {return $false}
$Array = [array]($All | foreach {$_.ToString()})
$Pred = [Predicate[String]]{$args[0] -eq $ShouldBe.ToString()}
[Array]::TrueForAll($Array,$Pred) # <-- [bool]
} #End
} #function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment