如何将Windows hosts文件主机名、IP与MAC关联导出至CSV?
解决Hosts条目与IP、MAC关联导出CSV的方案
原代码的核心问题在于将IP和主机名拆分存储为两个独立数组,遍历IP时无法对应回原主机名,且使用Format-List会破坏对象结构,导致Export-Csv无法正确识别属性。以下是修正后的实现:
修正后的代码
$Pattern = '^(?<IP>\d{1,3}(\.\d{1,3}){3})\s+(?<Host>.+)$' $File = "$env:SystemDrive\Windows\System32\Drivers\etc\hosts" $interface = Get-NetIPInterface -InterfaceAlias Ethernet -AddressFamily IPv4 # 初始化结果集合 $results = @() (Get-Content -Path $File) | ForEach-Object { if ($_ -match $Pattern) { $currentIP = $Matches.IP $currentHost = $Matches.Host try { # 获取对应IP的MAC地址 $neighborInfo = Get-NetNeighbor -AddressFamily IPv4 -AssociatedIPInterface $interface -IPAddress $currentIP -ErrorAction Stop $macAddress = $neighborInfo.LinkLayerAddress } catch { Write-Warning "MAC地址未找到: $currentIP" $macAddress = "Not Found" } # 创建包含完整关联信息的自定义对象 $results += [PSCustomObject]@{ HostName = $currentHost IPAddress = $currentIP MACAddress = $macAddress } } } # 导出CSV,避免类型信息并指定UTF-8编码防止乱码 $results | Export-Csv -Path "hosts_mapping.csv" -NoTypeInformation -Encoding UTF8
关键修改说明
- 关联IP与主机名:直接在遍历Hosts文件的每个匹配条目时,同步处理IP和主机名,避免数组错位问题。
- 保留对象结构:移除
Format-List,直接提取LinkLayerAddress属性,确保输出为标准PS对象,让Export-Csv能正确识别字段。 - 完善异常处理:MAC地址未找到时,赋值明确标识
Not Found,保证CSV字段完整性。 - 优化导出参数:添加
-NoTypeInformation去除CSV头部的类型注释,-Encoding UTF8避免中文主机名乱码。
注意事项
- 需以管理员权限运行PowerShell,否则可能无法读取Hosts文件或获取网络邻居信息。
- 若你的网卡别名不是
Ethernet,需修改Get-NetIPInterface的-InterfaceAlias参数(可通过Get-NetIPInterface命令查看本机网卡别名)。
内容的提问来源于stack exchange,提问作者Vylex
相关产品推荐
相关产品推荐

