2014-10-03 23 views
0

我有以下功能,我提供3个数组作为变量Powershell的字表单列误差

$columnHeaders = @('Ticket ID', 'Date Raised', 'Title', 'Status') 
$columnproperties = @('number', 'opened_at', 'short_description', 'state') 
$contents 

$内容具有匹配上面的列中的数据的多行,但是有时可以仅具有1点的行。当$内容只有1行时,下面的函数出错并且不打印数据。

使用ISE我将问题追溯到$ contents.count没有显示值,为什么?有没有办法绕过它?

function TableOutput ($columnHeaders, $columnProperties, $contents){ 
    # Number of columns 
    $columnCount = $columnHeaders.Count 


    # Create a new table 
    $docTable = $Word.ActiveDocument.Tables.Add($Word.Selection.Range,$contents.Count,$columnCount) 

    # Table style 
    $doctable.Style = "Adapt Table" 


    # Insert the column headers into the table 
    for ($col = 0; $col -lt $columnCount; $col++) { 
     $cell = $docTable.Cell(1,$col+1).Range 
     $cell.Font.Bold=$true 
     $cell.InsertAfter($columnHeaders[$col]) 
    } 
    $doctable.Rows.Add() > Null 

    # Load the data into the table 
    $i = 1 
    $j = $contents.Count 
    for($row = 2; $row -lt ($contents.Count + 2); $row++){ 
     if($row -gt 2){ 
     } 
     for ($col = 1; $col -le $columnCount; $col++){ 
      Write-Progress -Activity "Processing Table Information" -Status "Adding Row entry $i of $j" -PercentComplete (100*$i/$j) 
      $cell = $docTable.Cell($row,$col).Range 
      $cell.Font.Name="Calibri" 
      $cell.Font.Size="10" 
      $cell.Font.Bold=$FALSE 
      $cell.Text = $contents[$row-2].($columnProperties[$col-1]) 
     } 
     $i++ 

    } 
    $doctable.Columns.AutoFit() 
} 

任何帮助,非常感谢。

回答

1

将$ content作为字符串数组转换,看看它是否对您没有好处。

function TableOutput ($columnHeaders, $columnProperties, [string[]]$contents){ 

编辑:对不起,是我不好,你逝去的对象与性质的广告descripbed在$ columnheaders,所以你需要将其强制转换为对象的数组来代替:

function TableOutput ($columnHeaders, $columnProperties, [object[]]$contents){ 

测试在我的结尾,它可以很好地处理传递给函数的1个对象,以及传递给函数的两个对象的数组。

+0

没有不工作,当我这样做没有数据输出到表,只是创建空的行。 – 2014-10-03 15:45:37

+0

好的,对不起,我只是看着你的函数的内部工作。你需要声明它为'[object []]',因为它是一个不是字符串的对象数组。 – TheMadTechnician 2014-10-03 16:01:43

+0

感谢您的帮助,这工作了一个治疗:) – 2014-10-06 08:04:47