Variable Output in Email

$listmanagers = Get-ADUser -Filter * -SearchBase "OU=Non Employees,OU=Users,OU=Accounts,DC=Contoso,DC=com" -Properties Manager| where-object { $_.manager -ne $null} | %{(Get-AdUser $_.Manager)} | select-object -Unique
ForEach ($listmanager in $listmanagers)
{

$contractemp = Get-ADUser -Filter { manager -eq $listmanager} -SearchBase "OU=Non Employees,OU=Users,OU=Accounts,DC=Contoso,DC=com" -Properties Manager 
$managername = get-aduser $listmanager | select-object name

$body ="    Dear $managername,"
Send-Mailmessage -smtpServer $smtpServer -from $from -to $recipient -subject $subject -body $body -bodyasHTML 

If I run that query, everything works as expected, but when the email is sent, the manager name looks like this:
Dear @{name=Manager Name},

What do I need to change, so that it reads

Dear Manager Name,

Thanks,
J

You have a couple of options. $managername is a object containing the name. So you can do either expand the property to return a string:

$managername = get-aduser $listmanager | select-object -ExpandProperty name

or reference the property as [object].property

$body ="    Dear $managername.name," 

Use Select-Object’s -ExpandProperty parameter, instead of -Property (which is what you are using when you pass arguments positionally):

$managername = get-aduser $listmanager | select-object -ExpandProperty name

The difference is that $managername will now be a String object, instead of a PSObject that has a String property called “Name”. When you see that hashtable-like syntax in a string, it’s a dead giveaway: “@{name=Manager Name}”

If you do try to expand an object’s property inside a string, make sure to use the subexpression operator $(). This won’t work:

$body ="    Dear $managername.name,"

But this will:

$body ="    Dear $($managername.name),"

Thanks for the correction Dave. Also, you should take a look at here-strings if you are going to be compiling a message to the user for ease of formatting:

$managername = Get-ADUser jsmith | Select name

$body = @"
 Dearest $($managername.name),

 Some message blah blah blah

 Your technically apt IT God,

 Frank

"@

$body

Only catch is here-strings are picky with indentation and line breaks, but it’s much easy to format and read large amounts of text.

Thanks Guys - This is what worked for me

$managername = get-aduser $listmanager | select-object -ExpandProperty name
$body ="
    Dear $managername,
   

I still have much to do, but I am in the right direction…