2

I'm working on a PowerShell script that sends an email every time and error is encountered. I am trying the convert the $error[0] arraylist into the string but it's giving me the message:

You cannot call a method on a null-valued expression. 

Here's the chunk of code that I have in my catch block.

Catch [Exception]
{
    $Message = New-Object System.Exception "Error: " + $error[0].Exception.InnerException.ToString()
    Send-MailMessage -Port $port -smtpServer $smtpservername -to $to -from $from -subject $subject -body [string] $Message
    throw ($Message)
}

Any ideas on how to achieve this?

Starky
  • 135
  • 6

1 Answers1

4

You're incorrectly mixing PowerShell's two parsing modes, argument mode (as used in shells) and expression mode (as used in programming languages).

In order to use expressions as arguments in argument mode (as command arguments), you must enclose them in (...), the grouping operator:[1]

# WRONG
$Message = New-Object System.Exception "Error: " + $error[0].Exception.InnerException.ToString()

should be:

# OK - note the (...) around the string-concatenation operation:
$Message = New-Object System.Exception ("Error: " + $error[0].Exception.InnerException.ToString())

Similarly:

# WRONG
Send-MailMessage -Port $port -smtpServer $smtpservername -to $to -from $from -subject $subject -body [string] $Message

should be:

# OK - note the (...) around the [string] cast.
Send-MailMessage -Port $port -smtpServer $smtpservername -to $to -from $from -subject $subject -body ([string] $Message)

For more information on how unquoted tokens are parsed in argument mode, see this answer.


[1] There is one exception: if an argument starts with a variable reference, accessing a property of that variable or calling a method on it works as-is; e.g.: Write-Output $HOME.Length or Write-Output $HOME.ToLower(). See this answer for more information.

mklement0
  • 382,024
  • 64
  • 607
  • 775