6

I have been banging my head on this for a few hours and google is no help.

I have a function that is called in my code. The call looks like this:

$newData = @(CreateMailContactIfNeeded $entry)

The function that is called should always return a 2-element array. I confirm this right before the return statement of the called function:

# ... (inside CreateMailContactIfNeeded) ...
$tmpArr = @("$contactString" , "external")
Write-Host "length is" $tmpArr.length
Write-Host "Contact string is ->"$contactString"<-"
return $tmpArr

The length is always 2, and the contact string is always non-null. Sample output:

length is 2
Contact string is -> GMSContact-33<-

(I am unable to strip the leading space in the string, so I assume this is some sort of internal powershell string formatting or something)

HOWEVER, when I get back to the calling function, sometimes, but not always, the array that I build from the return value is length three:

if ($newData.length -eq 3) {
  Write-Host "Weird - array length is 3..."
}

Write-Host "Array length now is "$newData.length
foreach ($tmpVar in $newData) {
  Write-Host "Array entry is "$tmpVar
}

The first element of the 3-entry array is a valid string, but it is an artifact from earlier processing:

Weird - array length is 3...
Array length now is  3
Array entry is  Test User       <-- INVALID
Array entry is  GMSContact-33   <-- This should be first element
Array entry is  external        <-- This should be second element

Can someone explain to me what is possibly going on and how to fix it? Am I doing the array assignment incorrectly? Given the code above, how is it possible that "Test User" is getting inserted into the array?

EDIT: Full content of CreateMailContactIfNeeded below...

function CreateMailContactIfNeeded {
  param($CSVEntry)

  $email = $CSVEntry.EMAIL_ADDR

  Write-Host    "--> Searching for $email"
  Write-Host -n "----> In AD? "
   # Return if this person already exists as a user in AD
  if (IsInOurADDomain $CSVentry) {
    Write-Host -f green "YES."
    Write-Host "Returning "$email "= inhouse"
    return @("$email" , "inhouse")
  } else {
    Write-Host -n -f gray "NO. "
  }

  $contactString = "GMSContact-" + $CSVEntry.MEMBER_ID
  Write-Host "Contact string is now " $contactString

  # Check if mail contact already exists. If not, create it.
  Write-Host -n "In Contacts? "
  $object = Get-MailContact $email 2> $null

  if ($object -eq $null) {
    $displayName = $CSVentry.FIRST_NAME + " " + $CSVentry.LAST_NAME

    Write-Host -n -f gray "NO. "
    Write-Host -n "Creating contact... "

    $error.clear()
    New-MailContact -Name $contactString                    `
                    -DisplayName $displayName               `
                    -ExternalEmailAddress $email            `
                    -OrganizationalUnit $global:OU_CONTACT_STRING  
    if ($error[0] -ne $null) {
      Write-Host -f red "ERROR"
      Write-Error $error[0]
      return @("error","error")
    }
    # Derek says to do this to make it appear in alternate address book
    Set-MailContact -identity $contactString -customattribute1 "AB2"
    Write-Host -f green "SUCCESSFUL"
  } else {
    Write-Host -f green "YES"
  }
  Write-Host "Returning" $contactString "= external"
  $tmpArr = @("$contactString" , "external")
  Write-Host "length is" $tmpArr.length
  Write-Host "Contact string is ->"$contactString"<-"
  Write-Host "Contact string length is "$contactString.length
   foreach ($tmp in $tmpArr) {
     Write-Host "In function element is "$tmp
   }
   return $tmpArr
#  return @("$contactString" , "external")
}
4
  • 1
    Post the rest of your code, please. I'm sure it's somewhere in your function. Commented Sep 6, 2011 at 20:45
  • @JNK: Done. Full function content appears at bottom of post now. Thanks. Commented Sep 6, 2011 at 20:58
  • besides some awkward string manipulation it looks OK. Is the issue with the output or with the variable you are assigning to the output? If you just output the $tmpvar directly from the func is it OK? I would also recommend strongly typing your variables for stuff like this. Commented Sep 6, 2011 at 21:07
  • @JNK - everything in the function, before the return, looks perfect. The issue is that inside the function, the array is perfect. Length is two, and it contains exactly the content I want. As soon as it returns the array, and that return value is assigned to a new parameter, that new parameter is sometimes an array of length 3, where the first element is spurious and undesired. I have no idea what could be causing this. I am new to PS. Can you recommend the best way to cleanly and clearly set the type for any array? Am I returning an array value properly and assigning properly? Thanks! Commented Sep 6, 2011 at 21:11

3 Answers 3

10

In Poweshell, anything that is not "captured" is effectively "returned".

Let's take an example:

function test(){

    "starting processing"

    #do some processing

    write-host "starting different process"
    $output = @("first",second")
    return $output
}

When you do something like $myoutput =test, you will see that $myoutput actually has three elements - first,second as expected and also starting processing. Because the starting processing was uncaptured and was "returned" to the pipeline.

Wherever invalid "TEST USER" output is generated in your script, try capturing the output or pipe it to Out-Null or assign it to $null


Easy way to figure out where the extra element is being "returned" from.

Change the script so that you do not capture the output of the function in a varaiable. So leave it as CreateMailContactIfNeeded $entry

Before running the script, run Set-PsDebug -trace 1. Now, run the script - you should be able to see where TEST USER is being returned. Capture it as suggested above.

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

5 Comments

Awesome - I will indeed try that. Thanks!
@Larold - I have also added a suggestion that you can try to pin point where it is being returned.
Yup - this was exactly the problem. Thanks! Man, I bet this zaps a lot of people coming from a Perl / Unixy background.
@Larold - this also zaps those with programming background. I have myself had to learn this the hard way :) But it does have its uses once you understand it.
Just another note: The point in PowerShell is that you are explicitly encouraged to solve many things with the pipeline. That means that many lines will either be assignments or indeed statements that are intended to return something. At least that's the usual case for native PowerShell code. I frequently get the feeling that code that interfaces with AD, WMI or COM objects is uglier, but that's probably a historic artifact. I'm using it mostly for normal programming work instead of automation (heresy, I know) and I don't usually run into problems where it's ambiguous where output comes from.
4

Remember that return $something in PowerShell is just a way of saying

$something
return

That is, everything that falls out of a function is part of the return value; return just jumps out of the function.

So my guess is that somewhere before your return the value "Test User" falls out of a pipeline somewhere. Write-Host and assignments will never return anything, but New-MailContact maybe does. Or Set-MailContact. Those are the only two lines that could return anything that might inadvertently return something.

1 Comment

Ah! That is very useful to know - thank you. Let me dig in to my code, making sure that no spurious data makes its way through. This might be part of the problem.
0

I was having the same issue, and as suggested by @manojlds above, you need to specifically capture the output into some variable.

This issue occurred for me while using Invoke-Command $command functionality and anything the command outputs was being recorded into the return of the function.

Sample code :

$abc = MyFunc

function MyFunc
{
   $result = @()
   $command = "Some Command"
   Invoke-Command $command
   return $result
}

In above $result will be empty, but $abc will still have some output from Invoke-Command, given that command outputs something. So, to bypass it you can modify your code like this

$abc = MyFunc

function MyFunc
{
   $result = @()
   $command = "Some Command"
   $def = Invoke-Command $command
   return $result
}

i.e. store the output of the command into some variable and don't use it if not needed.

Comments

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.