Assign function result to a variable

I am working with a module to create new AD users with all parts included.

My function to create a mailbox works fine. But I am not able to use the return value. It´s not containg expected value.

function Add-EmailAccount{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[System.String]$userid,
[parameter(Mandatory = $true)]
[System.String]$company,
[Parameter(Mandatory = $true)]
[System.String]$adserver
)


switch ($company)
{
"Company1" { $emaildomain = "comany1.com" }
"Company2" { $emaildomain = "company2.com" }
}
#Connect to remote Exhange server and import session
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://server.net/PowerShell/ -Authentication Kerberos
Import-PSSession $Session

$user = Get-ADUser -Identity $userid -Server $adserver | Select-Object givenname, surname
#Add validation later. Check if exists
$email = "$($user.givenname).$($user.surname)@$emaildomain"

Write-Output "Enableling mailbox for user $userid on domaincontroller $adserver"
Enable-Mailbox -Identity "domain\$userid" -Database DB1 -DomainController $adserver | Out-Null
Set-Mailbox -identity domain\$userid -EmailAddressPolicyEnabled $false -DomainController $adserver | Out-Null
Write-Output "Setting $email as primary smtp for user $userid"
Set-Mailbox -identity domain\$userid -PrimarySmtpAddress $email -DomainController $adserver | Out-Null

Remove-PSSession $Session

return $email
}

And the main function that calls Add-EmailAccount

 $email = Add-SGEmailAccount -sgid $userid -company $company -adserver "dc.company.com"
Write-Output "Email: $email"

This gives me following output.

Email: tmp_2b3aazxn.vzq
Is this a result of the remote session to my Exchange server? How can i get the corret vaule from inside $session?

I think that’s the proxy module name which gets created when you do Import-PSSession.

Use Out-Null to avoid it getting in to the output.

You’re using Write-Output at several points in the function. This will add those strings to your return data as well. Write-Output and return send the data to the same place; they only differ in that return also exits the current scope and passes control back to the caller.