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?