在发送带附件的电子邮件的脚本结束后,PowerShell 仍然锁定文件
PowerShell still locks the file after the end of a script that sends email with attachment
我正在使用 PowerShell 和 System.Net.Mail.MailMessage
创建带有附件的电子邮件正文。我发现在我的脚本结束并且电子邮件发送成功后,目标文件仍然被 PowerShell 占用,直到我退出 PowerShell。有什么办法可以像在 C 或 Python 中关闭文件指针那样“关闭”它?
下面是我如何创建邮件消息并发送它的代码:
$message = New-Object System.Net.Mail.MailMessage $sender, $mailTo
$message.Subject = "Test email with attachment"
$message.Body = "See attachment."
$message.Attachments.Add("path\to\file")
$smtpClient = New-Object Net.Mail.SmtpClient($smtpHostname, $smtpPort)
$smtpClient.EnableSSL = $true
$smtpClient.send($message)
两个 System.Net.Mail.MailMessage
and System.Net.Mail.SmtpClient
implement the IDisposable
接口,这意味着你可以 - 并且应该 [1] - 在它们的实例上调用 .Dispose()
方法让它们释放所有完成后他们可能正在使用的资源:
$message.Dispose()
$smtpClient.Dispose()
[1] 如果您忽略这样做,持有的资源将 最终 被释放,即下一次 .NET 的垃圾收集器运行时,但是时间无法预测。
我正在使用 PowerShell 和 System.Net.Mail.MailMessage
创建带有附件的电子邮件正文。我发现在我的脚本结束并且电子邮件发送成功后,目标文件仍然被 PowerShell 占用,直到我退出 PowerShell。有什么办法可以像在 C 或 Python 中关闭文件指针那样“关闭”它?
下面是我如何创建邮件消息并发送它的代码:
$message = New-Object System.Net.Mail.MailMessage $sender, $mailTo
$message.Subject = "Test email with attachment"
$message.Body = "See attachment."
$message.Attachments.Add("path\to\file")
$smtpClient = New-Object Net.Mail.SmtpClient($smtpHostname, $smtpPort)
$smtpClient.EnableSSL = $true
$smtpClient.send($message)
两个 System.Net.Mail.MailMessage
and System.Net.Mail.SmtpClient
implement the IDisposable
接口,这意味着你可以 - 并且应该 [1] - 在它们的实例上调用 .Dispose()
方法让它们释放所有完成后他们可能正在使用的资源:
$message.Dispose()
$smtpClient.Dispose()
[1] 如果您忽略这样做,持有的资源将 最终 被释放,即下一次 .NET 的垃圾收集器运行时,但是时间无法预测。