powershell - 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++
}
解决方案
下面找出编号中的空白,并根据缺失的编号列出所有可用的名称:
# 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
用于将提取的数字与从数字到最高数字 ( ) 的(无间隙)范围(..
) 进行比较。默认情况下,会报告输入集合之间不同的元素,并且由于,从范围中丢失的那些提取的数字会直接输出。1
1..$highestNumber
-PassThru
$unusedNumbers.ForEach({ 'equipo' + $_ })
使用.ForEach()
数组方法为范围内未使用的数字构造名称列表。
推荐阅读
- ios - swift 5 自定义单元格图片点击
- excel - 如何使用 Excel VBA 宏使 excel 工作表受保护和不受保护?
- python - 用布尔数组屏蔽opencv bgr的最有效方法
- flutter - Flutter 在现有项目中构建 Web 不断失败
- swift - 了解组合中的 share()
- php - 在foreach中合并数组
- android - 错误:(19) 尝试安装 ADMOB 时,在包 'android' 中找不到属性 'appComponentFactory' 的资源标识符
- c# - 如何在 Access db vs 中按计数和名称选择行
- git - 扩展现有的 git 存储库,并定期、有选择地合并来自主项目的更新
- c# - 如果缺少 dll 文件,如何在 C# 项目中使用 interop.x.dll 文件?