You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中如何将ArrayList内无法连接的计算机元素移至另一集合

嘿,别担心作为脚本新手遇到这种问题太正常啦!我来帮你搞定这个移除无法连接主机的问题~

首先得指出你之前的一个小误区:你用$computerarray.$Computername这种方式去引用数组元素是不对的,ArrayList里的元素不是以属性形式存在的,得用索引或者值来操作才行。下面给你两种可靠的解决方案,你可以根据需求选:

方案1:先收集待删除主机,再批量移除

这种方式逻辑清晰,适合需要保留“无法连接主机列表”的场景:

  1. 先修正ArrayList的初始化和输入逻辑(用官方推荐的Add()方法更规范):
[System.Collections.ArrayList]$computerarray = @()
do {
    $ComputerName = Read-Host "Please enter the computer name"
    if ($ComputerName -ne '') {
        # 用[void]抑制Add方法返回的索引值输出
        [void]$computerarray.Add($ComputerName)
    }
} until ($ComputerName -eq '')
  1. 检测主机在线状态,收集无法连接的主机:
[System.Collections.ArrayList]$ComputersToDelete = @()

foreach ($computer in $computerarray) {
    # 用-Quiet参数直接返回布尔值,-Count 1加快检测速度,-ErrorAction避免冗余报错
    if (-not (Test-Connection -ComputerName $computer -Count 1 -Quiet -ErrorAction SilentlyContinue)) {
        Write-Host "$computer 无法连接,已标记待删除"
        [void]$ComputersToDelete.Add($computer)
    }
}
  1. 从原数组移除标记的主机:
foreach ($computer in $ComputersToDelete) {
    # 先判断元素是否存在,避免报错
    if ($computerarray.Contains($computer)) {
        [void]$computerarray.Remove($computer)
    }
}

方案2:倒序遍历直接移除(更高效,无需额外集合)

如果不需要保留“无法连接主机列表”,可以直接在遍历的时候删除元素,一定要倒序遍历索引,不然删除前面的元素后,后面的索引会错位导致漏删:

[System.Collections.ArrayList]$computerarray = @()
do {
    $ComputerName = Read-Host "Please enter the computer name"
    if ($ComputerName -ne '') {
        [void]$computerarray.Add($ComputerName)
    }
} until ($ComputerName -eq '')

# 倒序遍历索引,从最后一个元素往前处理
for ($i = $computerarray.Count - 1; $i -ge 0; $i--) {
    $currentComputer = $computerarray[$i]
    if (-not (Test-Connection -ComputerName $currentComputer -Count 1 -Quiet -ErrorAction SilentlyContinue)) {
        Write-Host "$currentComputer 无法连接,已直接移除"
        [void]$computerarray.RemoveAt($i)
    }
}

关键知识点总结

  • 操作ArrayList时,要用它的内置方法:Add()添加元素,Remove()按值删除,RemoveAt()按索引删除,比用+=更高效也更规范
  • 遍历数组并删除元素时,正序遍历会导致索引偏移,所以要么倒序遍历索引,要么先收集所有要删除的元素再批量处理
  • Test-Connection加上-Quiet参数可以直接返回布尔值,非常适合做条件判断,再配合-ErrorAction SilentlyContinue可以避免弹出不必要的错误提示

内容的提问来源于stack exchange,提问作者Dylan Johnson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:04:18