我没有使用 PowerShell 的经验,我被要求创建这个脚本作为我的一个 friend 的恩惠。该脚本应该读取 csv 文件(这些文件除了时间和主机之外具有不同的列,这些列在所有文件中都是通用的),并将其内容输出到以下格式的 JSON 文件中:
CSV 文件包含列:
主机|留言 |时间 |严重程度 |来源|
{
"time": 1437522387,
"host": "dataserver992.example.com",
"event": {
"message": "Something happened",
"severity": "INFO",
"source": "testapp"
#...All columns except for time and host should be under "event"
}
}
*唯一有保证的列是时间和主机。所有其他列标题因文件而异。
这是我迄今为止所拥有的一部分:
$csvFile = Import-Csv $filePath
function jsonConverter($file)
{
#Currently not in use
$eventString = $file| select * -ExcludeProperty time, host
$file | Foreach-Object {
Write-Host '{'
Write-Host '"host":"'$_.host'",'
Write-Host '"time":"'$_.time'",'
Write-Host '"event":{'
#TODO: Put all other columns (key, values) under event - Except for
time and host
Write-Host '}'
}
}
jsonConverter($csvFile)
关于如何逐行提取剩余的列,将其内容输出为键、值 JSON 格式(如上面的示例)的任何想法? 谢谢!
最佳答案
假设您的 csv 如下所示:
"host","message","time","severity","source"
"dataserver992.example.com","Something happened","1437522387","INFO","testapp"
这个脚本:
$filepath = '.\input.csv'
$csvData = Import-Csv $filePath
$NewCsvData = foreach($Row in $csvData){
[PSCustomObject]@{
time = $Row.time
host = $Row.host
event = ($Row| Select-Object -Property * -ExcludeProperty time,host)
}
}
$NewCsvData | ConvertTo-Json
将输出这个Json:
{
"time": "1437522387",
"host": "dataserver992.example.com",
"event": {
"message": "Something happened",
"severity": "INFO",
"source": "testapp"
}
}
关于json - 在 PowerShell 中从 csv 创建特定的 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54041551/