Quantcast
Channel: PowerShell General
Viewing all articles
Browse latest Browse all 10624

Not reading variable properly when script run from the shell.

$
0
0

Hello,

I think this is probably something I'm doing incorrectly.

I'm doing a simple script to send an email with the Net.Mail.MailMessage class. This is because with that it's easy for me to construct HTML and have inline images.

But a strange thing is happening. I'm using the following code to send the mail

 

$smtpServer="smtp.ourinternalserver.com"
$MailFrom= "address@from.co.uk"
$msg=new-objectNet.Mail.MailMessage
$smtp=new-objectNet.Mail.SmtpClient($smtpServer)
$msg.From=$MailFrom
$msg.IsBodyHTML=$true
$msg.Subject=$Subject

$toRecipients=Get-Content c:\PASendEmails\userlists\TextFile.txt | Get-Mailbox
foreach($recipientin$toRecipients)
{
$msg.to.Add($recipient.PrimarySmtpAddress)
}

$msg.Body=$MailHTML
$smtp.Send($msg)

This works fine if I just use the $msg.to.Add method = and then one recipient so the HTML and the mail is fine.
But if I use the above method to cycle through a text file of aliases, and this is where it get's odd, it works in an IDE (PowerGui in my case) but not at the shell.
If I run it at the shell I get 

 

Cannot convert argument "0", with value: "name@domain.com", for "Add" to type "System.Net.Mail.MailAddress":
"Cannot convert the "name@domain.com" value of type "Microsoft.Exchange.Data.SmtpAddress" to type "System.Net
.Mail.MailAddress"."
At C:\PASendEmails\PA-SendEmail3-Yourenowprotectedagainstdataloss.ps1:467 char:15
+    $msg.to.Add <<<< ($recipient.PrimarySmtpAddress)
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
Exception calling "Send" with "1" argument(s): "A recipient must be specified."
At C:\PASendEmails\PA-SendEmail3-Yourenowprotectedagainstdataloss.ps1:498 char:11
+ $smtp.Send <<<< ($msg)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

it's definitely bringing back the right email with get-mailbox the error above has the right email address in it (obviously I put in name@domain.com).
And the exact same code works in the IDE.
I think it has something to do with the way PowerShell outputs an object because if I output that variable to a text file as well it looks like this.

as you can see there's loads of spaces I've highlighted after the SMTP Address, and also 3 carriage returns after. 
I'm not sure how to get rid of that space, or the heading if need be, if that's the issue. Any advice would be much appreciated.

 


Viewing all articles
Browse latest Browse all 10624

Latest Images

Trending Articles



Latest Images