2014年12月14日 星期日

Powershell Script 自動備份 + 發信 + mount SAMBA

此篇是 PowerShell 的第二篇進階 Script,用於自動化備份並且要發信告知管理者

目標流程

1. 設定一些環境變數、mount samba,並利用 test-Patch 確認 mount 成功。當然最後你也可以用 test-File 來確認備份完成。

2. 設定 send smtp server 資訊,smtp server、sender、Recipients、主旨、信件內容、附件

3. 用 if 判斷 $Patch 是否存在

- 否 = print "Directory Already exists" 並且 unmount samba


- 是 = 建立當天日期並備份檔案 來源→目的→匯出 log → send mail → unmount samba




 
#System Variable for backup Procedure 

$date = Get-Date -Format yyyMMdd
net use w: \\192.168.100.110\Content /user:backupadm backuppwd
New-PSDrive -Name "Backup" -PSProvider Filesystem -Root "\\192.168.100.110\Content"
$source = "D:\BackupS"
$destination = "backup:\$date"
$path = test-Path $destination

#Email Variables

$smtp = "192.168.100.10"
$from = "PowerShell_Backup@shazi.twbbs.org"
$to = "eric@sun.net.tw"
$body = "Log File of SunnetEric bacupk is attached, backup happens on of Date: $date"
$subject = "Sunnet Eric Backup on $date"

# Backup Process started

if ($path -eq $true) {
write-Host "Directory Already exists"
Remove-PSDrive "Backup"
} elseif ($path -eq $false) {
cd backup:\
mkdir $date
copy-Item -Recurse $source -Destination $destination
$backup_log = Dir -Recurse $destination | out-File "$destination\backup_log.txt"
$attachment = "$destination\backup_log.txt"
#Send an Email to User
send-MailMessage -SmtpServer $smtp -From $from -To $to -Subject $subject -Attachments $attachment -Body $body -BodyAsHtml
write-host "Backup Sucessfull"
cd c:\

Remove-PSDrive "Backup"
}

 

另存成 BackupSendMain.ps1 並用 powershelll 工作排程執行就可以囉 !!

Orignal From: Powershell Script 自動備份 + 發信 + mount SAMBA

沒有留言:

張貼留言