TheInfamousOne
TheInfamousOne

Reputation: 205

PowerShell Function Return Value additional values I don't need

When I query AD return a SIP address. It's not a problem. the string comes back perfectly. But I will be constantly using this code, so I need to write a function. The function returns what I need, but it also returns additional things I don't need.

All I am doing is query AD and getting the sip address. eg:[email protected]. I'm splitting the email address at the "@" symbol and returning what is to the left of it. Again, the code returns John.Smith perfectly.

But when I add this code inside a function, I get returns that looks like this.

0
1
2
John.Smith

Here is what I have.

Function CheckSIP {

    $loggedOnUser = (get-WmiObject win32_process -Filter "Name='explorer.exe'"|Select -First 1).GetOwner().User

    $strFilter = "(&(objectCategory=User)(mailnickname=$loggedOnUser))"
    $objDomain = New-Object 

    System.DirectoryServices.DirectoryEntry("LDAP://OU=Offices,dc=OurNetwork,dc=net")
    $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
    $objSearcher.SearchRoot = $objDomain
    $objSearcher.PageSize = 1000
    $objSearcher.Filter = $strFilter
    $objSearcher.SearchScope = "Subtree"

    $colProplist = "name", "mail", "mailnickname"
    foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}

    $colResults = $objSearcher.FindAll()

    foreach ($objResult in $colResults){

        $objItem = $objResult.Properties
        [string]$UserName = $objItem.name 
        [string]$sipaddress = $objItem.mail
        [string]$mailnickname = $objItem.mailnickname
    }

    $theSIP = $sipaddress.Split("@")[0]

    return $theSIP
}

$mySIPaddress = CheckSip

All I need is john.smith

I'm sure I'm syntax handicapped somewhere, I just don't know where to look.

Upvotes: 1

Views: 1543

Answers (1)

mklement0
mklement0

Reputation: 437428

In PowerShell, it is not only a function's return statement that creates output:

  • any statement in the function can write to the output stream.
  • furthermore, any statement that produces output by default writes to the output stream, unless that output is captured in a variable or suppressed (via >$null / | Out-Null or via $null = ...)

In your case it is the following statement (which returns the index at which $i is inserted into the StringCollection) instance:

$objSearcher.PropertiesToLoad.Add($i)

Simply suppressing its output will remove the 0, 1, 2, values from your output:

$null = $objSearcher.PropertiesToLoad.Add($i)

As an aside, you could simplify your code:

  • Use $env:USERNAME in lieu of (get-WmiObject win32_process -Filter "Name='explorer.exe'"|Select -First 1).GetOwner().User
  • Use the ActiveDirectory PowerShell module with its Get-ADUser cmdlet, which makes working with AD much easier.

Upvotes: 2

Related Questions