Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell adds other values to return value of function

It seems that PowerShell adds an additional variable to the return value of a function.

The function subfoo2 itself delivers the correct values, but as soon as PowerShell jumps back to the postion where I called the function (in foo1), value contains the value of an other variable ($msg)

(Have a look at the comments in the code)

writeMessageLog($msg){
   ...
   Add-Content $msg
   ...
}
   subfoo2{
   writeMessageLog($msg)
   return $UserArrayWithValues #During Debug, $Array is fine (1)
}
   foo1{
   $var = subfoo2 $UserArray # $var has now the value of $msg and $UserArrayWithValues (2)
   #do something with var
}

Realcode:

function WriteLog 
{
param ( [string] $severity , $msgNumber, [string] $msg )
...

        $msgOut = $date + ... + $msg 
        Add-Content $msgout ( $msgOut )
...
}

function getFeatures
{
    writelog 'I'  1002  $true $true "Load Features"
    $Features = importCsv -pPath $FeatureDefintionFilePath 
    Writelog 'I'  1000  $true $true "Features Loaded"
    return $Features # $Features has value as expected (1)
}


function GetUserFeatures ($pUserObject)
{

    $SfBFeatures = ""
    $SfBFeatures = getFeatures #SfBFeaures has Value of $msg and $Features (2)
...
}

Do I use the functions/return values wrong? What could lead to such behavior? Is it an issue if i call a function within a function?

If I remove $msgOut = $date + ... + $msg in writeMessageLog, the values are fine.

I'm pretty lost right now, and have no ideas where this comes from. Any ideas welcome.

like image 459
16 revs Avatar asked Sep 05 '25 10:09

16 revs


2 Answers

This is how powershell works, basically everything that you print out will be returned as the function output. So don't output extra stuff. To force something to not output stuff you can do:

$null = some-command_that_outputs_unwanted_things

since everybody is obsessed with Out-Null I'll add this link showing several other ways to do that.

like image 151
4c74356b41 Avatar answered Sep 09 '25 01:09

4c74356b41


Within a function, everything you don't assign or pipe to a consuming cmdlet will get put to the pipeline and returned from the function - even if you don't explicit return it. In fact the return keyword doesn't do anything in PowerShell so the following is equivalent:

function Test-Func
{
   "Hello World"
}

function Test-Func
{
   return "Hello World"
}

So it looks like your writeMessageLog puts anything on the pipeline thus you have to either assign the value to anything:

$notUsed = writeMessageLog($msg)

or (prefered) pipe it to the Out-Null cmdlet:

writeMessageLog($msg) | Out-Null
like image 41
Martin Brandl Avatar answered Sep 09 '25 00:09

Martin Brandl