【问题标题】:Powershell Script to move and rename files用于移动和重命名文件的 Powershell 脚本
【发布时间】:2015-06-03 16:58:49
【问题描述】:

我有大约 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
}

【问题讨论】:

    标签: powershell powershell-2.0 powershell-3.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
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多