json - 从JSON创建CSV文件时Powershell脚本性能不佳

标签 json csv powershell

我的以下代码存在性能问题。我想将一些信息从JSON文件解析为CSV。 JSON本身大约有20万行。此转换的性能不佳,因为处理此类文件需要1个小时以上。

我认为问题可能出在Add-Content函数上,因为我使用的是普通硬盘。如果您看到代码的任何改进或可以做的任何更改,请让我知道吗?

$file = "$disk\TEMP\" + $mask
$res = (Get-Content $file) | ConvertFrom-Json
$file = "$disk\TEMP\result.csv"

Write-Host "Creating CSV from JSON" -ForegroundColor Green
Add-Content $file ("{0},{1},{2},{3},{4}" -f "TargetId", "EventType", "UserId", "Username", "TimeStamp")

$l = 0
foreach ($line in $res) {
    if($line.EventType -eq 'DirectDownloadCompleted' -and $line.TargetDefinition -eq 'GOrder') { 
        #nothing here
    } elseif($line.EventType -eq 'DirectDownloadCompleted' -and $line.TargetDefinition -eq 'GFile') {
        Add-Content $file ("{0},{1},{2},{3},{4}" -f
        $line.AssetId, $line.EventType, $line.UserId, $line.UserName, $line.TimeStamp)
        $l = $l + 1
    } else {
        Add-Content $file ("{0},{1},{2},{3},{4}" -f $line.TargetId, $line.EventType, $line.UserId, $line.UserName, $line.TimeStamp)
        $l = $l + 1
    }
}

最佳答案

好的,我想这里有几节课。首先,请不要重写Export-CSV cmdlet。而是将您的信息转换为对象数组,然后一次将其全部输出。这样可以使您只需要写入一次文件,这将显着提高速度。另外,当ForEach>If>IfElse>Else cmdlet中已经存在此功能时,请勿执行Switch。尝试这样的事情:

$Results = Switch($res){
    {$_.EventType -eq 'DirectDownloadCompleted' -and $_.TargetDefinition -eq 'GOrder'}{Continue}
    {$_.EventType -eq 'DirectDownloadCompleted' -and $_.TargetDefinition -eq 'GFile'}{$_ | Select @{l='TargetId';e={$_.AssetId}},EventType,UserId,Username,TimeStamp;Continue}
    Default {$_ | Select TargetId,EventType,UserId,Username,TimeStamp}
}
$Results | Export-CSV $file -NoType
$l = $Results.Count

关于json - 从JSON创建CSV文件时Powershell脚本性能不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33787508/

相关文章:

android - Android 上的 Google Drive Rest API

ios - 从服务器获取 JSON 文件时的内容丢失

php - 使用 PHP json_encode() 和 MySQL 返回一个 JSON 对象以传递给 jQuery 函数

c++ - 解析逗号分隔的 std::string

powershell - $ _。SubString($ _。IndexOf (“”))Powershell帮助

powershell - 在 PowerShell 中连接到 CRM 2016 IFD

用于用户名验证的正则表达式模式

json - PostgreSQL JSON 查询返回 NULL

安卓导出数据到csv

Python:类型错误:不可散列的类型: 'slice'