I've got a PowerShell script on PowerShell v4.0 (Windows 7 x64 SP1) that creates a pretty complex DataTable. I wanted to be able to place that DataTable code anywhere pretty easily, so I decided to wrap it in a simple function, like so:
function Get-UserDataTable
{
$DataTable = New-Object -TypeName System.Data.DataTable -ArgumentList 'User';
$NewColumn = $DataTable.Columns.Add('Id',[System.Int32]);
$NewColumn.AllowDBNull = $false;
$NewColumn.Unique = $true;
$NewColumn = $DataTable.Columns.Add('FirstName',[System.String]);
$NewColumn.MaxLength = 64;
$NewColumn = $DataTable.Columns.Add('MiddleName',[System.String]);
$NewColumn.MaxLength = 64;
$NewColumn = $DataTable.Columns.Add('LastName',[System.String]);
$NewColumn.MaxLength = 64;
return $DataTable;
}
However, that code always returns a null object. I tried Write-Output $DataTable, return $DataTable.Copy(), and $DataTable, but the function is still always null.
So, I thought I might try adding some rows. I can always clear the DataTable, and it'd still be less coding this way:
function Get-UserDataTable2
{
$DataTable = New-Object -TypeName System.Data.DataTable -ArgumentList 'User';
$NewColumn = $DataTable.Columns.Add('Id',[System.Int32]);
$NewColumn.AllowDBNull = $false;
$NewColumn.Unique = $true;
$NewColumn = $DataTable.Columns.Add('FirstName',[System.String]);
$NewColumn.MaxLength = 64;
$NewColumn = $DataTable.Columns.Add('MiddleName',[System.String]);
$NewColumn.MaxLength = 64;
$NewColumn = $DataTable.Columns.Add('LastName',[System.String]);
$NewColumn.MaxLength = 64;
$NewRow = $DataTable.NewRow();
$NewRow.Id = 1;
$NewRow.FirstName = 'Test';
$NewRow.MiddleName = '';
$NewRow.LastName = 'User';
$DataTable.Rows.Add($NewRow);
$NewRow = $DataTable.NewRow();
$NewRow.Id = 2;
$NewRow.FirstName = 'Other';
$NewRow.MiddleName = 'Test';
$NewRow.LastName = 'User';
$DataTable.Rows.Add($NewRow);
return $DataTable;
}
Nope. This function returns a [System.Object[]] containing individual [System.Data.DataRow]. An object array of DataRows.
How can I return a DataTable from a function in PowerShell?
return ,$DataTable;.DataTableconsidered as collection, although it does not implementIEnumerable.return ,$DataTable;appears to work. Totally forgot about that. Enter as answer and I'll accept.HashSetvsDataTable. Rest is the same: you return collection from function and do not see that collection, but individual collection elements packed into array. If you disagree, feel free to answer question by your own answer or find a better duplicate question to close.