You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

编写脚本获取单台PC网络连接的名称、设备名及网络类别等信息

解决单台PC网络信息全量获取的PowerShell脚本方案

嘿,我刚好知道怎么解决这个问题!你之前用Get-WmiObject只拿到部分信息,是因为Win32_NetworkAdapterConfiguration确实不包含网络连接名称和网络类别这些字段——咱们得结合几个不同的PowerShell命令来凑齐所有需要的信息。

针对Windows 8/Server 2012及以上系统的现代方案

这个方案用PowerShell的NetTCPIP模块命令,比WMI更高效且输出更直观:

# 获取已联网的网络连接配置(包含名称、类别、接口索引)
$connectionProfiles = Get-NetConnectionProfile -ErrorAction SilentlyContinue

# 获取启用状态的网络适配器(包含设备名称、接口索引)
$activeAdapters = Get-NetAdapter | Where-Object { $_.Status -eq 'Up' }

# 关联两类信息并输出结构化结果
foreach ($profile in $connectionProfiles) {
    $matchedAdapter = $activeAdapters | Where-Object { $_.InterfaceIndex -eq $profile.InterfaceIndex }
    [PSCustomObject]@{
        '主机名' = $env:COMPUTERNAME
        '网络连接名称' = $profile.Name
        '设备名称' = $matchedAdapter.Description
        '网络类别' = $profile.NetworkCategory
    }
}

脚本说明:

  • Get-NetConnectionProfile:直接拿到网络连接的名称(比如“以太网”)和网络类别(枚举值为Public/Private/DomainAuthenticated,完全符合你的需求)
  • Get-NetAdapter:获取网卡的设备名称(比如“Intel(R) Ethernet Connection”),通过InterfaceIndex字段和连接配置关联
  • 主机名用系统环境变量$env:COMPUTERNAME直接获取,简单高效

针对Windows 7/Server 2008 R2的兼容方案

如果你的系统版本比较旧,NetTCPIP模块不可用,可以用WMI类组合来实现:

# 获取网络连接配置文件
$wmiProfiles = Get-WmiObject -Class Win32_NetworkConnectionProfile -ErrorAction SilentlyContinue

# 获取已启用的网络适配器
$wmiAdapters = Get-WmiObject -Class Win32_NetworkAdapter -Filter "NetEnabled='True'"

# 关联并转换网络类别为可读文本
foreach ($profile in $wmiProfiles) {
    $matchedAdapter = $wmiAdapters | Where-Object { $_.InterfaceIndex -eq $profile.InterfaceIndex }
    $networkCategoryText = switch ($profile.NetworkCategory) {
        0 { 'Public' }
        1 { 'Private' }
        2 { 'DomainAuthenticated' }
        default { 'Unknown' }
    }
    [PSCustomObject]@{
        '主机名' = (Get-WmiObject Win32_ComputerSystem).Name
        '网络连接名称' = $profile.Name
        '设备名称' = $matchedAdapter.Description
        '网络类别' = $networkCategoryText
    }
}

脚本说明:

  • Win32_NetworkConnectionProfileNetworkCategory是数字枚举,需要通过switch转换为你需要的文本格式
  • 主机名通过Win32_ComputerSystem类的Name属性获取

这两个方案都能完整输出你需要的所有信息,你可以根据自己的系统版本选择对应的脚本~

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

火山引擎 最新活动