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

PowerShell脚本优化:将密钥文件数据整理为Name/Expire列CSV

问题描述

我写了一段PowerShell脚本,想从key.txt文件里提取Name和Expire信息,导出成带Name、Expire列标题的CSV,但输出格式不符合预期。以下是原脚本、key.txt的示例内容,求帮忙修正脚本,实现每条记录的名称与对应过期日期正确存入CSV。

原PowerShell脚本

$txtFilePath = "C:\Reports\key.txt"

$pattern1 = "id" 
$pattern2 = "names"
$pattern3 = "expires" 

$extractedData = @()

$lines = Get-Content -Path $txtFilePath
foreach ($line in $lines) {
if ($line -match $pattern1) {
$id = $line -replace '.*id*', ''
$extractedData += [pscustomobject]@{
  'Field' = '$line'
  'Value' = $id
   }
}
elseif ($line -match $pattern2) {
  $expires = $line -replace '.*name*', ''
  $extractedData += [namepscustomobject]@{
       'Field' = 'name'
       'Value' = $name
    }
}
    elseif ($line -match $pattern3) {
    $Expiry = $line -replace '.*expires*', ''
    $extractedData += [pscustomobject]@{
    'Field' = 'Expiry'
    'Value' = $Expiry
}
}
}


 $extractedData | Format-Table -AutoSize

 $extractedData | Export-Csv -Path "C:\Reports\Results\output.csv" -NoTypeInformation

key.txt示例内容

{
"attributes": {
  "created": "2019-07-03T14:55:51+00:00",
  "enabled": true,
  "expire": "2299-12-25T07:28:38+00:00",
  "notBefore": null,
  "recoverableDays": 90,
  "recoveryLevel": "Recoverable",
  "updated": "2022-09-26T20:32:13+00:00"
 },
 "contentType": "",
"id": "https://prod-ukb2c-keyvault-ne.vault.azure.net/secrets/azure-log-analytics-workspace-customer-id",
"managed": null,
"name": "azure-log-analytics-workspace-customer-id",
"tags": {}
  },
  {

key.txt片段

},
"contentType": "text/plain; tfmanaged=true",
"id": "https://prodtctkvne.vault.azure.net/secrets/prod-helios",
"managed": null,
"name": "prod-helios-ado-app-secret",
"tags": {}
},
{
"attributes": {
"created": "2023-12-07T09:52:56+00:00",
"enabled": true,
"expires": null,
"notBefore": null,
"recoverableDays": 90,
"recoveryLevel": "Recoverable",
"updated": "2023-12-07T09:52:56+00:00"
},
"contentType": "text/plain; tfmanaged=true",
"id": "https://prodtctkvne.vault.azure.net/secrets/prod-helios",    
"managed": null,
"name": "prod-helios-databricks-app-id",
"tags": {}
},

修正方案

原脚本的核心问题是用逐行正则匹配的方式处理JSON数据,既容易出错又效率低下,同时存在变量名错误、正则表达式不严谨、对象定义语法错误等问题。正确的做法是直接解析JSON结构来提取数据,以下是修正后的实现:

步骤1:修复key.txt的JSON格式

你的key.txt是多个独立JSON对象的片段,需要将其转换为合法的JSON数组:在文件开头添加[,结尾添加],并确保对象之间用逗号分隔(注意最后一个对象后不要留多余逗号)。

如果不想手动修改文件,也可以用脚本自动补全格式,见下方可选脚本。

步骤2:修正后的PowerShell脚本

$txtFilePath = "C:\Reports\key.txt"
$outputCsvPath = "C:\Reports\Results\output.csv"

# 读取文件并解析为JSON对象数组
$secrets = Get-Content -Path $txtFilePath -Raw | ConvertFrom-Json

# 提取目标字段,兼容示例中expire/expires两种字段名
$extractedData = $secrets | ForEach-Object {
    [pscustomobject]@{
        Name   = $_.name
        Expire = switch ($_.attributes.PSObject.Properties.Name) {
                    { $_ -contains 'expire' } { $_.attributes.expire }
                    { $_ -contains 'expires' } { $_.attributes.expires }
                    default { $null }
                }
    }
}

# 输出到控制台并导出CSV
$extractedData | Format-Table -AutoSize
$extractedData | Export-Csv -Path $outputCsvPath -NoTypeInformation -Encoding UTF8

可选:自动修复JSON格式的脚本

如果无法手动修改key.txt,可使用以下脚本自动补全合法JSON结构:

$txtFilePath = "C:\Reports\key.txt"
$outputCsvPath = "C:\Reports\Results\output.csv"

# 读取原始内容并修复为合法JSON数组
$rawContent = Get-Content -Path $txtFilePath -Raw
$fixedContent = "[" + $rawContent.Trim().TrimStart('{').TrimEnd('}').Trim(',') + "]"
$secrets = $fixedContent | ConvertFrom-Json

# 提取字段逻辑与上方一致
$extractedData = $secrets | ForEach-Object {
    [pscustomobject]@{
        Name   = $_.name
        Expire = switch ($_.attributes.PSObject.Properties.Name) {
                    { $_ -contains 'expire' } { $_.attributes.expire }
                    { $_ -contains 'expires' } { $_.attributes.expires }
                    default { $null }
                }
    }
}

$extractedData | Format-Table -AutoSize
$extractedData | Export-Csv -Path $outputCsvPath -NoTypeInformation -Encoding UTF8

脚本说明

  1. 直接解析JSON:使用-Raw参数一次性读取文件内容,避免逐行处理破坏JSON结构,再通过ConvertFrom-Json直接转换为PowerShell对象,无需依赖易出错的正则匹配。
  2. 兼容字段差异:针对示例中同时存在expire和expires两种字段名的情况,脚本自动判断并提取对应值。
  3. 正确构建输出对象:每个秘钥条目作为一个独立对象,包含Name和Expire属性,导出CSV时直接生成预期的列格式。
  4. 指定UTF8编码:导出CSV时添加-Encoding UTF8参数,避免中文名称出现乱码问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:10:56