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

Net-Connection Test结果无法通过Export-Excel正确导出求助

Test-NetConnection结果导出Excel问题解决

问题根源

  1. Test-NetConnection返回的默认对象包含大量嵌套属性,直接导出会导致列混乱
  2. 未显式构造包含目标列的自定义输出对象
  3. 可能存在CSV端口列类型不匹配(字符串转数字)的问题

完整解决代码

# 读取服务器端口列表
$serverList = Import-Csv -Path ".\serverlist.csv"

# 存储测试结果的数组
$testResults = @()

foreach ($entry in $serverList) {
    # 执行端口连通性测试,静默模式返回布尔值
    $connStatus = Test-NetConnection -ComputerName $entry.'server name' -Port $entry.port -InformationLevel Quiet
    
    # 构造符合导出要求的自定义对象
    $result = [PSCustomObject]@{
        ComputerName = $entry.'server name'
        Port         = [int]$entry.port
        Status       = if ($connStatus) { "连通成功" } else { "连通失败" }
        Date         = Get-Date -Format "yyyy-MM-dd"
        Time         = Get-Date -Format "HH:mm:ss"
    }

    $testResults += $result
}

# 导出到Excel,自动调整列宽+表头加粗
$testResults | Export-Excel -Path ".\端口连通测试结果.xlsx" -AutoSize -BoldTopRow

关键细节说明

  • 针对CSV中列名带空格的情况(server name),用$entry.'server name'正确引用
  • 将端口列强制转换为[int]类型,避免导出时出现格式异常
  • 用-InformationLevel Quiet简化Test-NetConnection的返回结果,便于快速判断连通状态
  • 显式定义输出对象的列名,确保导出Excel时完全匹配需求:ComputerName、Port、Status、Date、Time

常见报错处理

  • 若提示找不到Export-Excel命令,先安装ImportExcel模块:
    Install-Module -Name ImportExcel -Scope CurrentUser -Force
    
  • 若测试超时,可在Test-NetConnection中添加-TimeoutMs 5000参数调整超时时间(单位:毫秒)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:53:17