【问题标题】:Append multiple rows to a csv in Powershell在 Powershell 中将多行附加到 csv
【发布时间】:2020-02-17 00:40:00
【问题描述】:

我正在尝试创建一个脚本,该脚本通过每天通过 API 运行多个查询来检索数据,然后将值附加到 CSV 文件中的多个新行。如何将所有值附加到 CSV 文件中的多个新行。

#Category 1 Queries

$C1_Range1 = 'API query...'
$C1_Range2 = 'API query...'
$C1_Range3 = 'API query...'

#Category 2 Queries

$C2_Range1 = 'API query...'
$C2_Range2 = 'API query...'
$C2_Range3 = 'API query...'

...

Export-Csv 'C:\path\to\your.csv' -NoType -Append

我试图避免在每次查询后导出为 CSV。是否可以在 powershell 中构建一个可以一次性附加到 CSV 的表?

这是我想要的 CSV 输出的示例

DATE, CATEGORY, RANGE, VALUE        #ColumnName
...
09/10/2019, CAT1, RANGE3, 34567     #Existing Values
09/10/2019, CAT2, RANGE1, 12345
09/10/2019, CAT2, RANGE2, 98776
09/09/2019, CAT2, RANGE3, 45654
10/10/2019, CAT1, RANGE1, 12345 
10/10/2019, CAT1, RANGE2, 23456
10/10/2019, CAT1, RANGE3, 34567
10/10/2019, CAT2, RANGE1, 98765
10/10/2019, CAT2, RANGE2, 87654
10/10/2019, CAT2, RANGE3, 34567     #I want to append all the new queries to the bottom

例如,在追加新行之前,我将如何向哈希表添加新行...

'$NewRow = Date + Category + Range + Query 1
Add to bottom of $table

$NewRow = Date + Category + Range + Query 1
Add to bottom of $table

$NewRow = Date + Category + Range + Query 1
Add to bottom of $table'

...
And then I can append to the CSV

您的帮助将不胜感激!谢谢你

【问题讨论】:

  • 您是否有可能在集合中捕获查询 (@())?
  • 请澄清个别查询结果是否需要预处理才能将它们交给Export-Csv。
  • 您好,感谢您的建议。是的,API 查询需要在脚本中运行,然后才能交给 Export-CSV

标签: powershell csv append


【解决方案1】:

如果您可以将查询组合到一个集合中,您可以遍历它们并以PSCustomObject 的形式创建每个条目。这是另一个问题中的一个示例:PSObject array in PowerShell。

$coll = @(
   Range1,
   Range2,
   Range3,
   ...
)

$table = foreach ($item in $coll)
{
   [PSCustomObject]@{
      'Date' = Get-Date
      'Category' = $item.Category
      'Range' = $item.Name
      'Value' = $item.Value
   }
}

您可以导出为 CSV 的最终报告。

【讨论】:

  • 嗨,Alex_P,我已经尝试过了,但我仍然有点不确定该怎么做。我在我的问题中包含了另一个例子。有什么建议?谢谢
  • 即使你有额外的例子,你的问题是什么?你得到一个错误还是太慢了?正如我所写,我将首先创建 $table 变量,最后将表附加到现有文件中。
猜你喜欢
  • 2012-04-06
  • 1970-01-01
  • 1970-01-01
  • 2020-11-07
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
  • 2020-06-28
  • 1970-01-01
相关资源
最近更新 更多