Nesse breve tutorial iremos aprender como configurar um Script de Backup para Windows usando o robocopy em Power Shell com relatório sendo enviado por e-mail.
Script está disponível no seguinte endereço.
http://stackoverflow.com/questions/15672388/robocopy-sending-email-attachment-appending-file-name
#*============================================= #* Base variables #*============================================= $SourceFolder = "C:\SourceFolder" $DestinationFolder = "C:\DestinationFolder" $Logfile = "C:\Robocopy.log" $Subject = "Robocopy Results: Copy Purpose - Location to Location" $SMTPServer = "smtp.server.com" $Sender = "Server <email@address.com>" $Recipients = "User1 <email@address.com>" $Admin = "Admin <email@address.com>" $SendEmail = $True $IncludeAdmin = $True $AsAttachment = $False #*============================================= #* GMAIL variables #*============================================= #$SMTPServer = "smtp.gmail.com" #$cred = New-Object System.Net.NetworkCredential("username", "password"); # Add "-UseSsl -Credential $cred" to the Send-MailMessage #*============================================= #* SCRIPT BODY #*============================================= # Change robocopy options as needed. ( http://ss64.com/nt/robocopy.html ) Robocopy $SourceFolder $DestinationFolder /MIR /R:2 /W:5 /LOG:$Logfile /NP /NDL # The following attempts to get the error code for Robocopy # and use this as extra infromation and email determination. # NO OTHER CODE BETWEEN THE SWITCH AND THE ROBOCOPY COMMAND Switch ($LASTEXITCODE) { 16 { $exit_code = "16" $exit_reason = "***FATAL ERROR***" #$IncludeAdmin = $False #$SendEmail = $False } 8 { $exit_code = "8" $exit_reason = "**FAILED COPIES**" #$IncludeAdmin = $False #$SendEmail = $False } 4 { $exit_code = "4" $exit_reason = "*MISMATCHES*" $IncludeAdmin = $False #$SendEmail = $False } 2 { $exit_code = "2" $exit_reason = "EXTRA FILES" $IncludeAdmin = $False #$SendEmail = $False } 1 { $exit_code = "1" $exit_reason = "Copy Successful" $IncludeAdmin = $False #$SendEmail = $False } 0 { $exit_code = "0" $exit_reason = "No Change" $SendEmail = $False $IncludeAdmin = $False } default { $exit_code = "Unknown ($LASTEXITCODE)" $exit_reason = "Unknown Reason" #$SendEmail = $False $IncludeAdmin = $False } } # Modify the subject with Exit Reason and Exit Code $Subject += " : " + $exit_reason + " EC: " + $exit_code # Test log file size to determine if it should be emailed # or just a status email If ((Get-ChildItem $Logfile).Length -lt 25mb) { If ($IncludeAdmin) { If ($AsAttachment) { Send-MailMessage -From $Sender -To $Recipients -Cc $Admin -Subject $Subject -Body "Robocopy results are attached." -Attachment $Logfile -DeliveryNotificationOption onFailure -SmtpServer $SMTPServer } Else { Send-MailMessage -From $Sender -To $Recipients -Cc $Admin -Subject $Subject -Body (Get-Content $LogFile | Out-String) -DeliveryNotificationOption onFailure -SmtpServer $SMTPServer } } Else { If ($AsAttachment) { Send-MailMessage -From $Sender -To $Recipients -Subject $Subject -Body "Robocopy results are attached." -Attachment $Logfile -DeliveryNotificationOption onFailure -SmtpServer $SMTPServer } Else { Send-MailMessage -From $Sender -To $Recipients -Subject $Subject -Body (Get-Content $LogFile | Out-String) -DeliveryNotificationOption onFailure -SmtpServer $SMTPServer } } } Else { # Creat the email body from the beginning and end of the $Logfile $Body = "Logfile was too large to send." + (Get-Content $LogFile -TotalCount 15 | Out-String) + (Get-Content $LogFile | Select-Object -Last 13 | Out-String) # Include Admin if log file was too large to email Send-MailMessage -From $Sender -To $Recipients -Cc $Admin -Subject $Subject -Body $Body -DeliveryNotificationOption onFailure -SmtpServer $SMTPServer #Exclude Admin if log file was too large to email #Send-MailMessage -From $Sender -To $Recipients -Subject $Subject -Body $Body -DeliveryNotificationOption onFailure -SmtpServer $SMTPServer } #*============================================= #* END OF SCRIPT: Copy-RobocopyAndEmail.ps1 #*=============================================
Nos meus testes não consegui autenticar o script usando tls em servidor remoto usando o powershell, então optei por instalar um servidor smtp local.
Para enviar o e-mail faz se necessário a instalação do hMailServer trata-se de um servidor de e-mail Open Source para Windows. Usaremos esse servidor para fazer relay com algum servidor válido na internet.
Acesse o link para baixar e instalar o hMailServer
É necessário ter o DotNet Framework 2.0 instalado para prosseguir com a instalação.
1 – Crie um domínio local
2 – crie uma conta de usuário qualquer Ex. admin@minhaempresa.local
3 – Desabilite serviços que não serão utilizados
4 – Configure um servidor de e-mail para relay
Para testar utilize essa linha de comando no Power Shell.
Send-MailMessage -From admin@minhaempresa.local -To admin@minhaempresa.com.br -Subject Teste -Body "Teste ok." -DeliveryNotificationOption onFailure -SmtpServer localhost
Sobre o Autor