2

I have a PowerShell 5.0 function which I'm trying to use to return a data table that is used in some downstream activities. However, it seems to return duplicates everytime I place this into a variable as so:

function GetTable {

    $tbl = New-Object "System.Data.DataTable" 
    $tbl.Columns.Add("testNum").DataType = [string]

    for($i=0; $i -lt 3; $i++){
            $tbl.Rows.Add($i)
    }
    Write-Host $tbl.Rows.Count
    return $tbl
}

$test = GetTable
$test.Rows.Count

This outputs:

3
6

Why does the function duplicate the data when returning the data table?

1 Answer 1

4

That is because the Add method returns the added element so it also gets to the pipeline. You can simply fix that by pipe the result to Out-Null:

function GetTable {

    $tbl = New-Object "System.Data.DataTable" 
    $tbl.Columns.Add("testNum").DataType = [string]

    for($i=0; $i -lt 3; $i++){
            $tbl.Rows.Add($i) | Out-Null
    }
    Write-Host $tbl.Rows.Count
    return $tbl
}

$test = GetTable
$test.Rows.Count
Sign up to request clarification or add additional context in comments.

2 Comments

Would this be the same case for the Columns.Add method? Or is the fact that the datatype is being specified to it prevent that from happening?
In PowerShell, everything that you call that returns something and you don't assign to a variable or pipe to anything gets put to the pipeline and will be returned even you don't use the return keyword. So if the Columns.Add method returns anything the answer is yes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.