Reputation: 817
I have about 8 PDF files that need to be moved from one folder to another and renamed with the date extension 'filename_yyyymmdd'.
If one of the files are not in the source file path, then I need the script to email an error message, but continue looping through to check for the other files.
The subject and body of the email message needs to be unique to each file so the user knows which file didn't get transferred or wasn't available in the source directory.
The script below is what I have been using, but I don't know how to loop through each file and send a unique email for each failure.
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 [email protected] -To [email protected] `
-Subject "Files Failed to Transfer to Archive Folder!" `
-Body "The error message is: '$ErrorMessage'" `
-SmtpServer smtp...
Break
}
Upvotes: 1
Views: 2900
Reputation: 13537
Just rewrite this to use a Try/Catch/Finally approach, you're almost there!
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 [email protected] -To [email protected] `
-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
}
Upvotes: 1