1

Why does the simplified function below return more than the fruit name in the returned string?

For example, the write host INSIDE the function shows a fruit name. However the write host at the bottom (outside the function) shows fruit name (as expected) plus the database connection info (which is NOT desired/expected)

    #inside the function, write-host shows a fruit name as expected
    #outside the function (bottom line below) write-host shows extra things such as the connection string (for example: "server=myserver;database=mydb;userid=myuser....thefruitname")
    
    function Get_A_SINGLE_FRUIT_NAME{
        $queryString = "SELECT top 1 fruitname from FROM fruits"; 
        $dbConnectionString = "a-real-conn-string-was-here"   

        $dbConnectionString

        Invoke-Sqlcmd -ConnectionString $edwConnectionString -Query $queryString -MaxCharLength 50000 -OutVariable sqlReturn |Out-Null   
    
        foreach($queryResultRow in $sqlReturn){
            try{
                [String]$returnString = $queryResultRow.fruitname
                write-host("fruitname found:"+$returnString);
            }Catch{
                $_.Exception.Message
                $returnString="No fruitname found"
            }
            Break
        }
        return $returnString 
    }


$qryOut = Get_A_SINGLE_FRUIT_NAME
write-host("qry out:"+$qryOut);
1
  • Can you provide sanitized sample output of Write-Host "qry out: $qryOut"? Commented Sep 7, 2021 at 19:44

1 Answer 1

3

I found the issue. When a PowerShell function returns a value, it also returns any other values output to the pipeline which may have occurred inside the function before the return statement.

See also: Function return value in PowerShell

So I removed the extraneous line which contained ONLY $dbConnectionString, and now the function returns ONLY the expected value.

Sign up to request clarification or add additional context in comments.

2 Comments

I was thinking something like this was the problem, though I was thinking perhaps Invoke-SqlCmd might return connection information. In this case it was the $dbConnectionString variable which was omitted in your original sample.
I suggest reading this answer of mine to learn about output streams and redirection. You can use additional cmdlets to display information on the screen that isn't operable (without some tweaking) programmatically. E.g. you could display your connection string if you want without having it returned via the pipeline and assigned to your variable.

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.