我正在使用scriptlet从SQL查询创建文件,然后通过电子邮件发送给自己。我想在通过电子邮件发送完成后删除该文件,但是在脚本完成之前它一直被Powershell锁定,因此它会出错。如何解锁/卸载它创建的文件并在同一脚本中将其删除?我确定有办法! :)
#Connection Strings
$Database = "somedb"
$Server = "localhost"
#SMTP Relay Server
$SMTPServer = "172.16.150.10"
#Export File
$AttachmentPath = "e:\folder\filename.csv"
# Connect to SQL and query data, extract data to SQL Adapter
$SqlQuery = "select * from some.where"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Data Source=$Server;Initial Catalog=$Database;Integrated Security = True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$nRecs = $SqlAdapter.Fill($DataSet)
$nRecs | Out-Null
#Populate Hash Table
$objTable = $DataSet.Tables[0]
#Export Hash Table to CSV File
$objTable | Export-CSV $AttachmentPath
#Send SMTP Message
$Mailer = new-object Net.Mail.SMTPclient($SMTPServer)
$From = "me@domain.org"
$To = "me@domain.org"
$Subject = "Report csv"
$Body = "Here is the data for the last month!"
$Msg = new-object Net.Mail.MailMessage($From,$To,$Subject,$Body)
$Msg.IsBodyHTML = $False
$Attachment = new-object Net.Mail.Attachment($AttachmentPath)
$Msg.attachments.add($Attachment)
$Mailer.send($Msg)
#THIS COMMAND IS NOT ABLE TO DELETE
Remove-Item $AttachmentPath
只是想弄清楚如何卸载/解锁它所制作的文件,这样我就可以在通过电子邮件发送后将其删除了,谢谢!
答案 0 :(得分:0)
根据 @PetSerAl 的建议,您可以使用$Msg
(Dispose()
)对象的MailMessage
方法来释放它使用的所有资源:< / p>
$Msg.Dispose()