Variable Output in Email

This topic contains 5 replies, has 3 voices, and was last updated by  Jeremy Anderson 4 years, 1 month ago.

  • Author
  • #16289

    Jeremy Anderson
    $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,


  • #16290

    Rob Simmers

    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 $," 
  • #16291

    Dave Wyatt

    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}"

  • #16292

    Dave Wyatt

    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 $,"

    But this will:

    $body ="    Dear $($,"
  • #16293

    Rob Simmers

    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 $($,
     Some message blah blah blah
     Your technically apt IT God,

    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.

  • #16302

    Jeremy Anderson

    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....

You must be logged in to reply to this topic.