首页 > 解决方案 > Powershell如何知道列表的元素是否连续编号

问题描述

我想知道是否所有的 PC 都在列表中,如果一个不在列表中,脚本会说我,列表可以用更多的 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++
}

标签: powershellsequence

解决方案


下面找出编号中的空白,并根据缺失的编号列出所有可用的名称:

# 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."
}

输出:

VERBOSE: The following names are available:
equipo4

笔记:

  • -replace '\D'从名称中删除所有非数字 ( \D) 字符并将结果字符串转换为以获取numbers[int[]]数组。

  • [Linq.Enumerable]::Max($numbers)找出其中的最大值(最高数)。请参阅.NET 文档

  • Compare-Object用于将提取的数字与从数字到最高数字 ( ) 的(无间隙)范围( ..) 进行比较。默认情况下,会报告输入集合之间不同的元素,并且由于,从范围中丢失的那些提取的数字会直接输出。11..$highestNumber-PassThru

  • $unusedNumbers.ForEach({ 'equipo' + $_ })使用.ForEach()数组方法为范围内未使用的数字构造名称列表。


推荐阅读