powershell - 无法发送Powershell电子邮件-您无法在空值表达式上调用方法

标签 powershell

我在我的本地计算机上运行此文件,但是当我在另一台计算机上尝试使用该文件时,该文件在同一位置等,则此错误失败。

function email 
{
  $emailSmtpServer = "smtp-mail.outlook.com"
  $emailSmtpServerPort = "587"
  $emailSmtpUser = "USERNAME"
  $emailSmtpPass = "PASSWORD"
  $attachment = "C:\BackupLog.log"
  $emailMessage.Attachments.Add($attachment)
  $emailMessage = New-Object System.Net.Mail.MailMessage
  $emailMessage.From = "myemail@hotmail.co.uk"
  $emailMessage.To.Add( "myemail@civil.lmco.com" )
  $emailMessage.Subject = "Database Issues"
  $emailMessage.IsBodyHtml = $true
  $emailMessage.Body = "Test"

  $SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer ,$emailSmtpServerPort )
  $SMTPClient.EnableSsl = $true
  $SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );

  $SMTPClient.Send( $emailMessage )
}

这是输出
PS C:\Users\XXLOCKRG1> email
You cannot call a method on a null-valued expression
At C:\database_backups\powershell scripts\functions\email.ps1:8 char:34
+ $emailMessage.Attachments.Add <<<< ($attachment)
+ CategoryInfo          : InvalidOperation: (Add:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

最佳答案

您有两行代码顺序错误:

$emailMessage.Attachments.Add($attachment) # $emailMessage isn't instantiated yet
$emailMessage = New-Object System.Net.Mail.MailMessage

应该:
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.Attachments.Add($attachment)

您必须先实例化对象,然后才能引用其成员。

关于powershell - 无法发送Powershell电子邮件-您无法在空值表达式上调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32275921/

相关文章:

具有多个输入字段的 Powershell 输入框

powershell - 无法从 Get-PSDrive 捕获 DriveNotFoundException

xml - 如何使用 powershell 更新 [xml] 属性中的字符串?

powershell - Sitecore Powershell 反序列化

powershell:get-winevent 没有消息数据?

c# cmdlet 如何获取正在使用的完整命令

Powershell - 如何设置 TCP 发送接收行结束字符? <CR> 与 <LF>

powershell - CSV文件保存在哪里?

authentication - 如何在不提示用户批处理的情况下以不同用户身份运行

powershell - 找不到位置参数