TIP – Watch Out! return values from functions in power shell…

by Dec 18, 2010

Ach SO!

Be carefull when writing functions that returns values in powershell.

Take this example:

 

function GetTaskDescriptionObject($sTitle, $sStatus, $iId)

{
  $objTask = New-Object System.Object |
                     Add-Member NoteProperty iID $iId -PassThru |
                     Add-Member NoteProperty sTitle $sTitle -PassThru |
                     Add-Member NoteProperty sStatus $sStatus -PassThru 

  return $objTask
}

All very nice you'll get a return entity of the type [System.Object], but now the programmer wants to do a little debuggin' to see the values of the parameters, so:

 

function GetTaskDescriptionObject($sTitle, $sStatus, $iId)

{
  $sTitle
  $sStatus
  $iId

  $objTask = New-Object System.Object |
                     Add-Member NoteProperty iID $iId -PassThru |
                     Add-Member NoteProperty sTitle $sTitle -PassThru |
                     Add-Member NoteProperty sStatus $sStatus -PassThru 

  return $objTask
}

Now we can see the variables printed in the console when we call the thing but, they will also be added to the return value resulting in this output:

a [System.Array] like this: {[string], [string], [string],[System.Object]}

But this is obvious you'd say, and yes it is, but for some of us coming from other languages it takes a little time to get used to that you can output stuff simply by typing the variable.

Results from function calls will also be displayed if you don't assign it, so it's important to assign their output to a variable, even if you don't use the return value.

 

So two things to avoid mangled return data from functions

1. Remember to remove any lines where you have typed variables to se their value

2. Remeber to assign output from function calls in a function to variables

As a powershell rookie I've learned this the hard way