我没有使用PowerShell的经验,因此我被要求创建此脚本来吸引我的一个朋友。该脚本应读取一个csv文件(这些文件在time和host以外的其他列中是不同的,这在所有文件中都是相同的),然后将其内容输出到以下格式的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格式的任何想法,如上面的示例所示? 谢谢!
答案 0 :(得分:4)
提供的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"
}
}
答案 1 :(得分:0)
如果您的Powershell版本是3.0或更高(应该):
Import-CSV $filepath | ConvertTo-JSON
完成!