Powershell - Checking for duplicate array elements

To support me, you can subscribe to the channel, share and like the videos, disable your ad blocker or make a donation. Thank you!

Hello,

A little Powershell code that lets you check for duplicate elements in an array.

# Defining the set of values with duplicates.
$array = 'A', 'B', 'C', 'C', 'B'
# Group objects and check for groupings greater than 1 (duplicates)
$Doublon = ($array | Group-Object | Where-Object -FilterScript {$_.Count -gt 1}).Values
# Check condition if duplicates or not
if ($null -eq $Doublon) { 'No duplicates'} else { $Doublon}
# Define the set of values with no duplicates
array = 'A', 'B', 'C'
# Check condition if duplicates or not
if ($null -eq $Doublon) { 'No duplicates'} else { $Doublon}
# And we can transform this code into a function
function Test-Doublon {
[CmdletBinding()] param (
[string[]]
$value )
#Group objects and check for groupings greater than 1 (duplicates)
$Doublon = ($Value | Group-Object | Where-Object -FilterScript {$_.Count -gt 1}).Values
# Check condition if duplicates or not
if ($null -eq $Doublon) { 'No duplicates'} else { $Doublon }
}
# Possible syntaxes
Test-doublon -value $array
Test-doublon $array
# Or as a function allowing pipeline values
function test-doublon {
[CmdletBinding()] param (
[array][Parameter(ValueFromPipeline)]
$Value )
#Group objects and check for groupings greater than 1 (duplicates)
$Doublon = ($Value | Group-Object | Where-Object -FilterScript {$_.Count -gt 1}).Values
# Check condition if duplicates or not
if ($null -eq $Doublon) { 'No duplicates'} else { $Doublon}
}
# Possible syntaxes
test-doublon -value $array
test-doublon $array
# Use the unary operator (the comma) to send our array as a single element, otherwise the pipeline will process each array value separately
,$array | test-doublon

Related links