来自CSV

时间:2018-03-09 16:24:18

标签: json powershell csv

使用PowerShell将CSV文件转换为Json需要一些帮助。我有一个脚本,使用PowerShell从Office365获取发送消息日志,并将它们导出到CSV文件中。然后,我将使用ConvertTo-Json cmdlet将CSV文件转换为Json。输出Json文件包含许多不必要的文本,使其难以阅读。例如,这就是我想要的:

{
 "SenderAddress":  "support@email.com",
 "RecipientAddress":  "zzzz@email.edu",
 "Subject":  "Microsoft PowerShell",
 "Status":  "Delivered",
 } 

以下是将CSV转换为Json后的结果:

{
        "value":  "\"support@email.com\",\"zzzz@email.edu\",\"Microsoft PowerShell\",\"Delivered\"",
        "PSPath":  "C:\\Logs\\Logs-1.csv",
        "PSParentPath":  "C:\\Logs",
        "PSChildName":  "Logs-1.csv",
        "PSDrive":  {
                        "CurrentLocation":  "Windows\\system32",
                        "Name":  "C",
                        "Provider":  "Microsoft.PowerShell.Core\\FileSystem",
                        "Root":  "C:\\",
                        "Description":  "Windows",
                        "MaximumSize":  null,
                        "Credential":  "System.Management.Automation.PSCredential",
                        "DisplayRoot":  null
                    },
        "PSProvider":  {
                           "ImplementingType":  "Microsoft.PowerShell.Commands.FileSystemProvider",
                           "HelpFile":  "System.Management.Automation.dll-Help.xml",
                           "Name":  "FileSystem",
                           "PSSnapIn":  "Microsoft.PowerShell.Core",
                           "ModuleName":  "Microsoft.PowerShell.Core",
                           "Module":  null,
                           "Description":  "",
                           "Capabilities":  52,
                           "Home":  "C:\\Users\\test",
                           "Drives":  "C D E"
                       },
        "ReadCount":  3

以下是我运行以将CSV文件转换为Json的PowerShell cmdlet。

Get-Content "C:\Logs\logs-1.csv" | ConvertTo-Json | Add-Content -Path "C:\Logs\logs-1.json

我也尝试了以下内容:

Get-Content "C:\Logs\logs-1.csv" |Select-Object -Property SenderAddress, RecipientAddress, Subject, Status ConvertTo-Json | Add-Content -Path "C:\Logs\logs-1.json

我去了这个结果:

{
    "SenderAddress":  null,
    "RecipientAddress":  null,
    "Subject":  null,
    "Status":  null
}

知道如何在没有额外信息的情况下将CSV文件正确转换为Json吗?

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

我猜您需要使用Import-Csv而不是Get-ContentGet-Item

尝试:

Import-Csv "C:\Logs\logs-1.csv" |
    ConvertTo-Json |
    Add-Content -Path "C:\Logs\logs-1.json"

或者:

Import-Csv "C:\Logs\logs-1.csv" |
    Select-Object -Property SenderAddress, RecipientAddress, Subject, Status |
    ConvertTo-Json |
    Add-Content -Path "C:\Logs\logs-1.json"

如果您打算覆盖C:\Logs\logs-1.json,请使用Set-Content代替Add-Content