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?

1
  • 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. Commented Aug 9, 2022 at 1:37

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.