如何用PowerShell解析OpenVPN用户数据并导出为CSV文件
使用PowerShell将OpenVPN sacli导出的JSON转换为CSV
步骤说明与代码实现
读取并解析JSON文件
先读取导出的文本文件,通过ConvertFrom-Json将JSON内容转为PowerShell可操作的对象:$jsonPath = "C:\path\to\your\exported_data.json" $jsonData = Get-Content -Path $jsonPath -Raw | ConvertFrom-Json提取属性并转换为可导出对象
导出的JSON外层以组/用户名为键,内层是对应属性集合。遍历这些键值对,将属性集合转为自定义PowerShell对象,还可添加组名属性方便溯源:$outputCsvPath = "C:\path\to\output.csv" # 可选:清空目标CSV,避免重复追加旧数据 if (Test-Path $outputCsvPath) { Remove-Item $outputCsvPath } foreach ($item in $jsonData.PSObject.Properties) { # 将属性哈希表转为自定义对象 $propsObject = [PSCustomObject]$item.Value # 添加组/用户名属性 $propsObject | Add-Member -MemberType NoteProperty -Name "Group/User" -Value $item.Name # 导出到CSV $propsObject | Export-Csv -Path $outputCsvPath -NoTypeInformation -Append }自定义输出格式(可选)
- 如果需要竖线分隔的格式(替代默认逗号),添加
-Delimiter "|"参数:$propsObject | Export-Csv -Path $outputCsvPath -NoTypeInformation -Append -Delimiter "|" - 如果只需要特定列,用
Select-Object指定要保留的属性:$propsObject | Select-Object -Property "c2s_dest_s", "group_declare", "Group/User" | Export-Csv -Path $outputCsvPath -NoTypeInformation -Append
- 如果需要竖线分隔的格式(替代默认逗号),添加
示例输出(竖线分隔格式)
以你提供的示例数据为例,输出内容如下:
c2s_dest_s|c2s_dest_v|group_declare|group_range.0|group_subnets.0|prop_autologin|prop_deny|prop_superuser|type|Group/User false|false|true|1.1.1.1-2.2.2.2|1.1.1.0/24|false|false|false|group|Development Access
内容的提问来源于stack exchange,提问作者Diego Laurora
相关产品推荐
相关产品推荐

