使用Powershell输出CSV

时间:2018-04-02 14:15:17

标签: rest api powershell

我从了解PowerShell脚本的输出CSV文件时遇到了问题!

我有一个对restapi服务器的请求,并且我得到一个包含10行或更多行的变量,例如:

>$ExpenseDescription 
Taxi to airport
Taxi to seaport
Taxi to spaceport
Taxi to home

我创建表

$tableExpenses=@"
Created On | Description | Expense Category
$ExpenseCreatedOnt | $ExpenseDescription |$ExpenseReport
$tableExpense|Out-File C:\Users\book.xls
$tableExpense|Out-File C:\Users\book.csv

作为输出文件,我得到 .xls .csv

所以问题是我在变量$ExpenseDescription中有10行,而OutFile包含 book.xls 中1个单元格中的所有10行!

如何在代码中拆分它们并以如下格式制作OutFile:

Created On | Description   | Expense Category
 10.10.2018|Taxi to airport| Money
 11.10.2018|Taxi to seaport| Visa

因为现在我在输出中有这个

Created On | Description   | Expense Category
10.10.2018 11.10.2018|Taxi to airport Taxi to seaport| Money Visa|

好的,我会添加更多代码)

的WebRequest

$ReportURI = ("https://api.rest.com/data/query") $ReportQuery = @{"q"="SELECT Category,Description,CreatedOn from Expense"} Try {$ResponseReport = Invoke-RestMethod -Method Post -Uri $ReportURI -Headers @{"Authorization" = $SessionId} -Body ( $ReportQuery | ConvertTo-Json) -ContentType "application/json" -ErrorAction Stop} Write-Host $ResponseReport} ConvertTo-Json $ResponseReport

变量

$ExpenseCreatedOn = $ResponseReport.CreatedOn $ExpenseDescription = $ResponseReport.Description $ExpenseReport = $ResponseReport.Category.Name

table_format

$tableExpense=@" Created On Description Expense Category $ExpenseCreatedOn $ExpenseDescription $ExpenseReport

$tableExpense|Out-File C:\Users\book.xls $tableExpense|Out-File C:\Users\book.csv

1 个答案:

答案 0 :(得分:1)

您没有输出CSV。使用Out-File,您正在导出文本文件。

假设您的变量包含一个字符串数组,您可以将它们编入索引以创建一个对象,然后使用Export-Csv导出该字符串:

foreach($i in 0..($ExpenseDescription.Count - 1)){

    [array]$tableExpenses += [pscustomobject]@{
        "Created On"       = $ExpenseCreatedOnt[$i]
        Description        = $ExpenseDescription[$i]
        "Expense Category" = $ExpenseReport[$i]
    }

}

$tableExpenses | Export-Csv C:\Users\book.csv -NoType
$tableExpenses | Export-Csv C:\Users\book2.csv -NoType -Delimiter "|"