3

I am writing a script in which I make many custom data tables, and for this reason I would like to make a function that generates the tables for me. Specifically, I would like the function to create the table and the columns of the table and then return that table so that the calling function can add row elements to the returned table. However, whenever I return a table without rows, I am told that I cannot add rows to it, since the element is empty. Here is what I have tried so far:

Function Generate-Table ($Name, [String[]]$ColumnNames, [Type[]]$DataTypes) {
    $table = New-Object system.Data.DataTable "$Name"

    for ($i = 0; $i -lt $ColumnNames.Length; $i++) {
        $col = New-Object system.Data.DataColumn $ColumnNames[$i],($DataTypes[$i])
        $table.columns.add($col)
    }
    return $table
}

$ColumnNames = @("Name", "Age")
$DataTypes = @([string], [int])
$table = Generate-Table "OutputTable" $ColumnNames $DataTypes

$row = $table.NewRow();
$row.Name = "Bob"
$row.Age = "20"
$table.Rows.Add($row);

$table

Which gives me the error:

You cannot call a method on a null-valued expression.
At C:\Users\mrpadmin\accounting\test.ps1:15 char:21
+ $row = $table.NewRow <<<< ();
    + CategoryInfo          : InvalidOperation: (NewRow:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Now, if I do the same, but replace line 13 with:

. Generate-Table "OutputTable" $ColumnNames $DataTypes

It correctly gives me the following output:

Name    Age
----    ---
Bob      20

Is there any way to return a data table object with no rows? And if not, is there another way to make a function that can return data tables ready to be filled with rows?

1 Answer 1

5

I think your problem will be solved by simply using the unary comma operator in front of the table you're returning:

return ,$table

Powershell does some interesting automatic unrolling of collections that implement IEnumerable. The comma operator will wrap your table in a single-object array, so when it gets automatically unrolled it will return back to the table. I don't know of a way to force Powershell to not do this.

Here is a reference to the operators.

Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly, thank you so much. I would never have figured that out on my own.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.