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

PowerShell:如何将无分隔符的非结构化数组解析为多列格式

非结构化数组转多列HTML展示方案

原始数据结构

待处理的数组写入文本后格式如下:

DC1
49600 Reachable 
49601 Reachable 
49602 Reachable 
49603 Reachable 
49604 Reachable 
49605 Reachable 
49606 Reachable 
49607 Reachable 
DC2
49600 Reachable 
49601 Reachable 
49602 Reachable 
49603 Reachable 
49604 Reachable 
49605 Reachable 
49606 Reachable 
49607 Reachable

实现代码

1. 数组结构化转换

遍历原始数组$Result,拆分DC分组与端口状态,生成结构化对象:

$reportItems = @()
$currentDC = $null

foreach ($line in $Result) {
    $line = $line.Trim()
    if ([string]::IsNullOrEmpty($line)) { continue }
    
    # 匹配DC分组标识
    if ($line -like 'DC*') {
        $currentDC = $line
        continue
    }
    
    # 拆分端口与状态
    $port, $status = $line -split '\s+', 2
    $reportItems += [PSCustomObject]@{
        DC名称 = $currentDC
        端口状态 = "$port $status"
    }
}

2. 生成HTML邮件正文

添加基础样式生成适配邮件的两列表格:

# 自定义表格样式
$css = @"
<style>
table {border-collapse: collapse; width: 60%; margin: 10px 0;}
th, td {border: 1px solid #ccc; padding: 6px 12px; text-align: left;}
th {background-color: #f5f5f5;}
</style>
"@

# 转换为HTML内容
$htmlBody = $reportItems | ConvertTo-Html -Property DC名称,端口状态 -Title "端口可达性检测结果" | Out-String
$htmlBody = $css + $htmlBody

3. 发送带格式的邮件

发送时指定正文为HTML格式即可:

Send-MailMessage -From "monitor@example.com" `
                 -To "admin@example.com" `
                 -Subject "端口可达性检测结果" `
                 -Body $htmlBody `
                 -BodyAsHtml `
                 -SmtpServer "smtp.example.com"

实现效果

输出的HTML邮件会自动展示为两列表格,DC名称对应所属的所有端口状态,符合预期的规整展示要求。

内容的提问来源于stack exchange,提问作者T-Heron

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:24:07