Powershell:返回函数中没有行的数据表

mrp*_*mrp 3 powershell return function rows

我正在编写一个脚本,我在其中创建了许多自定义数据表,因此我想创建一个为我生成表的函数.具体来说,我希望函数创建表和表的列,然后返回该表,以便调用函数可以向返回的表添加行元素.但是,每当我返回没有行的表时,我都被告知我无法向其添加行,因为该元素为空.这是我到目前为止所尝试的:

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
Run Code Online (Sandbox Code Playgroud)

这给了我错误:

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
Run Code Online (Sandbox Code Playgroud)

现在,如果我这样做,但用以下代码替换第13行:

. Generate-Table "OutputTable" $ColumnNames $DataTypes
Run Code Online (Sandbox Code Playgroud)

它正确地给了我以下输出:

Name    Age
----    ---
Bob      20
Run Code Online (Sandbox Code Playgroud)

有没有办法返回没有行的数据表对象?如果没有,是否有另一种方法可以创建一个函数,可以返回准备好用行填充的数据表?

gor*_*ric 5

我认为只需在您返回的表格前使用一元逗号运算符即可解决您的问题:

return ,$table
Run Code Online (Sandbox Code Playgroud)

Powershell做了一些有趣的自动展开实现IEnumerable的集合.逗号运算符将您的表包装在单个对象数组中,因此当它自动展开时,它将返回到表.我不知道有办法迫使Powershell不这样做.

这是对运营商的参考.