我正在编写一个PowerShell脚本,该脚本每次遇到错误时都会发送一封电子邮件。我正在尝试将$error[0]数组列表转换为字符串,但它给了我消息:
You cannot call a method on a null-valued expression.
这是我的catch块中的一大块代码。
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)
}
关于如何实现这一点,有什么想法吗?
您错误地混合了PowerShell的两种解析模式,参数模式(在shell中使用(和表达式方式(在编程语言中使用(。
要在参数模式中将表达式用作参数(作为命令参数(,必须将它们包含在(...)
中,分组运算符:[1]
# WRONG
$Message = New-Object System.Exception "Error: " + $error[0].Exception.InnerException.ToString()
应该是:
# OK - note the (...) around the string-concatenation operation:
$Message = New-Object System.Exception ("Error: " + $error[0].Exception.InnerException.ToString())
类似:
# WRONG
Send-MailMessage -Port $port -smtpServer $smtpservername -to $to -from $from -subject $subject -body [string] $Message
应该是:
# OK - note the (...) around the [string] cast.
Send-MailMessage -Port $port -smtpServer $smtpservername -to $to -from $from -subject $subject -body ([string] $Message)
有关如何在参数模式下解析未引用的令牌的更多信息,请参阅此答案。
[1]有一个例外:如果参数以变量引用开始,则访问该变量的属性或在其上调用方法即可正常工作;例如CCD_ 2或CCD_。有关详细信息,请参阅此答案