【发布时间】:2021-08-26 18:44:29
【问题描述】:
我正在使用一个简单的 PS 脚本。我需要将文件夹中的每个 txt 文件作为附件发送一封电子邮件,如果可以,请移动此文件。第一部分工作正常,问题是当我尝试移动文件时,总是被锁定。我读过很多关于 $smtp.dispose() 和 $attachment.dispose() 的帖子,但它对我不起作用。我总是收到此错误消息:
Move-Item : The process cannot access the file because it is being used by another process.
At C:\in\mail.ps1:41 char:5
+ Move-Item -Path $file -Destination C:\in\hist -force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (C:\in\CL..._0000345053.txt:FileInfo) [Move-Item], IOException
+ FullyQualifiedErrorId : MoveFileInfoItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand
这是脚本
#Connection Details
$username=””
$password=””
$smtpServer = “10.10.10.10”
$msg = new-object Net.Mail.MailMessage
#Change port number for SSL to 587
$smtp = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
#Uncomment Next line for SSL
#$smtp.EnableSsl = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential( $username, $password )
#From Address
$msg.From = "src@dom.com"
#To Address, Copy the below line for multiple recipients
$msg.To.Add(“dest@dom.com”)
#Message Body
$msg.Body=””
#Message Subject
$msg.Subject = “File”
#your file location
$files = Get-ChildItem "C:\in\*.txt"
$dest = "C:\in\hist"
Foreach($file in $files)
{
Write-Host "Attaching File :- " $file
$attachment = New-Object System.Net.Mail.Attachment –ArgumentList $file.FullName
$msg.Attachments.Add($attachment)
$smtp.Send($msg)
$attachment.Dispose()
$msg.Dispose()
$smtp.Dispose()
Move-Item -Path $file -Destination $dest -force
}
【问题讨论】:
-
为什么不使用内置的 cmdlet Send-MailMessage?
-
实际上在 powershell 中进行配置并不总是按预期工作。您可以尝试将发送邮件脚本作为单独的脚本并在另一个范围内调用它。其他方法是实现类似 C# 的
usingstackoverflow.com/a/42108420/5720797 -
为什么不在foreach 循环之后 移动文件?在此处添加暂停,然后使用
Move-Item -Path $files.FullName -Destination $dest -Force将它们全部移动
标签: powershell