我有大约8个PDF文件需要从一个文件夹移动到另一个文件夹,并使用日期扩展名'filename_yyyymmdd'重命名。
如果其中一个文件不在源文件路径中,那么我需要脚本通过电子邮件发送错误消息,但继续循环以检查其他文件。
电子邮件的主题和正文必须对每个文件都是唯一的,以便用户知道哪个文件没有传输或在源目录中不可用。
以下脚本是我一直在使用的,但我不知道如何遍历每个文件并为每次失败发送一封唯一的电子邮件。
Try
{
$a = "\\servername\Users\Desktop\agile.docx"
$b = "\\servername\Users\Desktop\Archive\agile.docx"
Move-item $a $b -ErrorAction stop
Function renameFile ($location, $filename, $extension)
{
$d = get-date -uformat "%Y%m%d"
$old = $location + $filename + $extension
$new = $filename + "_" + $d + $extension
rename-item $old $new
}
renamefile -location "\\servername\Users\desktop\Archive\" `
-filename "Agile" `
-extension ".docx"
}
Catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Send-MailMessage -From my.name@mycompany.com -To her.name@mycompany.com `
-Subject "Files Failed to Transfer to Archive Folder!" `
-Body "The error message is: '$ErrorMessage'" `
-SmtpServer smtp...
Break
}
答案 0 :(得分:1)
只需重写此内容即可使用Try / Catch / Finally方法,您几乎就在那里!
Try {Move-item $a $b -ErrorAction stop}
Catch {#if an error happens when moving the file, this code executes
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Send-MailMessage -From my.name@mycompany.com -To her.name@mycompany.com `
-Subject "Files Failed to Transfer to Archive Folder!" -SmtpServer smtp... `
-Body "The error message is: '$ErrorMessage', which was encountered when `
moving file $a"
RETURN
#use return to continue looping on the other files, where BREAK will exit the whole script
}