嗨,我有以下 PS 脚本,但输出不是我想要的安排方式,请任何人帮忙解决它。 它轮询一个 txt 文件以查找包含名称和过期时间的行,我想将其显示为具有名称和过期时间列标题的 CSV,并将每个名称和过期日期存储在帽子行中:
ID Name Expire
ID1 Name1 01/11/2024
ID2 Name2 05/12/2025
ID3 Name3 04/12/2024
我当前的 PS 脚本:
$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": {}
},
{
你的格式很糟糕,但假设输入是这样的,并且 id 字符串中间没有不正确的换行符
{
"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": {}
},
{
// More similar objects
}
那么该文件实际上是一种json,你可以简单地使用
ConvertFrom-Json
对其进行操作
PS C:\> $j = "[$(Get-Content C:\Reports\key.txt)]" | ConvertFrom-Json
PS C:\> $j | Select-Object -Property name, id, @{Name="attributes.expire"; Expression={($_.attributes.expire -as [datetime]).ToString("MM-dd-yyyy")}}
name id attributes.expire
---- -- -----------------
name1 id1 12-25-2299
name2 id2 12-25-2123