VSTSC's Community Server

Community Server: The platform that enables you to build rich, interactive communities.
VSTeamSystemCentral: Your Team System community!

Welcome to VSTSC's Community Server Sign in | Join | Help
in Search

Tim Benninghoff

A SQL Server DBA attempts a personal IT project and documents the (mis)adventures.

PowerShell Function Gotcha

In a renewed effort to read one tech book a month in 2010, I've restarted Bruce Payette's Windows PowerShell In Action just as I've been using PowerShell to solve a problem at work.  I was attempting to use a SendEmail function I found on a blog, and when I tried to call the function like this:

 SendEmail("someaddress@someplace.com","Someaddress@someplace.com","This is a subject","This is the body of the email");

I got the following error:

Exception setting "From": "Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Net.Mail.MailAddress"."
At C:\PowerShell\SendEmailTest.ps1:15 char:10
+     $msg. <<<< From = $From
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException

Exception calling "Add" with "1" argument(s): "The parameter 'addresses' cannot be an empty string.
Parameter name: addresses"
At C:\PowerShell\SendEmailTest.ps1:26 char:20
+         $msg.To.Add <<<< ($singleAddress)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Exception calling "Send" with "1" argument(s): "A from address must be specified."
At C:\PowerShell\SendEmailTest.ps1:56 char:17
+     $client.Send <<<< ($msg)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

 The parameter 'addresses' is an empty string?  How is that possible?  I clearly entered someaddress@someplace.com which is most definitely not an empty string.  Fortunately, I read about this PowerShell function gotcha in Mr. Payette's book on page 183, where goes on to describe things like PowerShell looking at the contents of parentheses as an expression and very smart people being tripped up by this.

To make a long story short, I should have called the function with the arguments separated by spaces, like:

 SendEmail "someaddress@someplace.com" "Someaddress@someplace.com" "This is a subject" "This is the body of the email";

I'll take this opportunity to plug the book again.  It's little pieces of advice like this that have saved me a ton of time as I've learned PowerShell.

Published Tuesday, January 26, 2010 7:34 PM by timbenninghoff
Filed under:

Comments

No Comments
Anonymous comments are disabled
Powered by Community Server (Personal Edition), by Telligent Systems