2
function Create-Container
(
    $SourceTable
)
{
    $datatable = [system.data.datatable]::new();
    $conn = [system.data.sqlclient.SqlConnection]::new("<connectionstring>");
    $da = [system.data.sqlclient.SqlDataAdapter]::new();
    $da.SelectCommand = [system.data.sqlclient.sqlcommand]::new(); 
    $da.SelectCommand.Connection = $conn;
    $da.selectcommand.CommandText = "<query>";
    $da.fill($datatable) | out-null;
    return $datatable;
}

Given the above PowerShell 7.2.5 function, I am unable to create an empty DataTable using the following operation:

$emptycontainer = Create-Container -SourceTable "sourcetable"

$emptycontainer is always null. However, placing the code in the main code path and not in a function works as expected. How do I get the function to return the empty DataTable?

swasheck
  • 4,644
  • 2
  • 29
  • 56
  • 1
    In short: PowerShell by default *enumerates* collections that you output from a function (whether or not you output them implicitly or via a `return` statement), i.e. it streams (outputs) the collection elements _one by one_. To output a collection *as a whole*, use `, $collection` (sic; or `return , $collection`) or, more explicitly but less efficiently, `Write-Output -NoEnumerate $collection`. See the linked duplicates for details. – mklement0 Aug 09 '22 at 01:37

0 Answers0