Doc
Doc

Reputation: 455

Powershell function string return value includes more than desired/expected

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);

Upvotes: 1

Views: 853

Answers (1)

Doc
Doc

Reputation: 455

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.

Upvotes: 3

Related Questions