【问题标题】:PowerShell still locks the file after the end of a script that sends email with attachment在发送带有附件的电子邮件的脚本结束后,PowerShell 仍会锁定文件
【发布时间】:2021-11-16 09:10:07
【问题描述】:

我正在使用 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)

【问题讨论】:

    标签: powershell mailmessage


    【解决方案1】:

    System.Net.Mail.MailMessageSystem.Net.Mail.SmtpClient 都实现了 IDisposable 接口,这意味着您可以 - 并且应该[1] - 在它们的实例上调用 .Dispose() 方法以使它们释放所有完成后他们可能会使用的资源:

    $message.Dispose()
    $smtpClient.Dispose()
    

    [1] 如果您忽视这样做,所持有的资源将最终被释放,即下一次 .NET 的垃圾收集器运行时,但时间是不可预测的.

    【讨论】:

    • 感谢您的回答。这确实解决了我的问题。
    • 我很感激,@ytingyeu。
    猜你喜欢
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 2017-09-06
    相关资源
    最近更新 更多