我一直在研究一个自动化的Word文档,并且遇到了一个我无法正确输出的foreach查询的问题。我有以下数据:
Date, server 1, server 2, server 8, server 12
19/08/2014, 4.24, 5.8, 2.05, 1.0
20/08/2014, 6.4, 3.8, 5.05, 2.1
但是我的脚本一直输出为:
Date, server 1, server 2, server 8, server 12
20/08/2014, 6.4, 3.8, 5.05, 2.1
基本上第一行被后续行覆盖,然后只有最后一行。
请参阅下面的代码:
#### Create Word Document ####
$word = New-Object -ComObject word.application
$word.visible = $true
$doc = $word.documents.add()
$selection = $word.selection
$nl = [Environment]::NewLine
# Create a new chart
$docChart = $Word.ActiveDocument.InlineShapes.AddChart()
$docChart.Chart.Type = "1"
$docChart.chart.SubType = "2"
$docChart.Chart.ChartStyle = "2"
$docChart.Chart.Legend.AutoScaleFont = "true"
$docChart.Chart.HasTitle = "True"
$docChart.Chart.ChartTitle.Formula = "VM Memory Consumption"
$cells = $docChart.chart.ChartData.Workbook.ActiveSheet.cells
$columns = $MyData | Get-Member -MemberType Properties | Select Name
foreach($column in $columns){
$row=1
$col++
$column2 = $column.Name
$cells.Item($Row,$col) = "$column2"
$MyData | ForEach-Object{
$Row1=2
$col
$date = $_.c3
$array = ($_ | Select-Object $Column2)."$Column2"
$Array | ForEach-Object{
$cells.Item($row1,$col) = "$array"
}
}
}
我真的很感激帮助解决这个问题。
谢谢, 史蒂夫
答案 0 :(得分:1)
以下代码已经解决了我的问题,基本上我在第一个foreach循环中创建$ row1变量,然后在第二个foreach循环中创建$ row1 ++,然后按预期放入数据。
#### Create Word Document ####
$word = New-Object -ComObject word.application
$word.visible = $true
$doc = $word.documents.add()
$selection = $word.selection
$nl = [Environment]::NewLine
# Create a new chart
$docChart = $Word.ActiveDocument.InlineShapes.AddChart()
$docChart.Chart.Type = "1"
$docChart.chart.SubType = "2"
$docChart.Chart.ChartStyle = "276"
$docChart.Chart.Legend.AutoScaleFont = "true"
$docChart.Chart.HasTitle = "True"
$docChart.Chart.ChartTitle.Formula = "VM Memory Consumption"
$docChart.chart.Legend.Position = "-4107"
$cells = $docChart.chart.ChartData.Workbook.ActiveSheet.cells
$columns = $MyData | Get-Member -MemberType Properties | Select Name
foreach($column in $columns){
$row=1
$col++
$row1=1
$column2 = $column.Name
$cells.Item($Row,$col) = "$column2"
$MyData | ForEach-Object{
$row1++
$date = $_.c3
$array = ($_ | Select-Object $Column2)."$Column2"
$Array | ForEach-Object{
$cells.Item($row1,$col) = "$array"
}
}
}