Powershell how to know if a list's elements are numbered consecutively

Viewed 94

I´m trying to know if all the PC are in the list and if one it´s not on the list the script will say me, the list can be modificate with more PC.


$equipos= "equipo1","equipo2","equipo3","equipo5"
[char]$nequipos = 1

for($i=0;$i -lt $equipos.count;$i++){
    [char]$num = $equipos[$i][6]
    if($num -ne $nequipos){
    write-host "equipo"$nequipos
    }
[char]$nequipos= $i++
}
2 Answers

The following finds the gaps in the numbering and lists all available names based on the missing numbers:

# Extract all numbers contained in the names.
[int[]] $numbers =  "equipo1", "equipo2", "equipo3", "equipo5" -replace '\D'
# Find the highest number.
$highestNumber = [Linq.Enumerable]::Max($numbers)

# Find all unused numbers.
$unusedNumbers = Compare-Object $numbers (1..$highestNumber) -PassThru

# Report results.
if ($unusedNumbers) {
  Write-Verbose -Verbose "The following names are available: "
  $unusedNumbers.ForEach({ 'equipo' + $_ })
} else {
  Write-Verbose -Verbose "No gaps in numbering found."
}

Output:

VERBOSE: The following names are available:
equipo4

Note:

  • -replace '\D' removes all non-digit (\D) characters from the names and casts the resulting strings to [int[]] in order to get an array of numbers.

  • [Linq.Enumerable]::Max($numbers) finds the maximum (highest number) among them. See the .NET docs.

  • Compare-Object is used to compare the extracted numbers to the (gap-less) range (..) of numbers from 1 to the highest one (1..$highestNumber). By default, the elements that are different between the input collections are reported and, thanks to -PassThru, those extracted numbers that are missing from the range are directly output.

  • $unusedNumbers.ForEach({ 'equipo' + $_ }) uses the .ForEach() array method to construct the list of names for the unused numbers in the range.

Assuming the names are unique, you can pick the highest number in the sequence and subtract the length of the list - that'll give you the number of gaps:

$equipos = "equipo1","equipo2","equipo3","equipo5" |Sort-Object {$_ -replace '^\D+' -as [int]} -Unique -Descending 

$highest = $equipos |Select -First 1
$number = $highest -replace '^\D+' -as [int]
if($number -gt $equipos.Length){
  "There are $($number - $equipos.Length) gap(s) in the list"
} 
else {
  "The list is contiguous"
}

Which, with the given sample values, will output:

There are 1 gap(s) in the list
Related