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.