У меня есть сценарий, который копирует резервные копии Veeam на NAS, в конце сценарий отправляет сообщение о состоянии.
Когда я запускаю скрипт вручную, я получаю письмо правильно, но в планировщике задач скрипт делает копию, но не отправляет почту. Я не понимаю почему.
Try {
#####Defining computer Uptime function#####
function Get-Uptime {
$os = Get-WmiObject win32_operatingsystem
$uptime = (Get-Date) - ($os.ConvertToDateTime($os.lastbootuptime))
$Display = "Uptime of " + $Uptime.Days + " days, " + $Uptime.Hours + " hours, " + $Uptime.Minutes + " minutes"
Write-Output $Display
}
$up = Get-Uptime
#####Defining encrypted password variable#####
$KeyFile = "AES.key"
$getkey = get-content $KeyFile
$day = Get-Date
#####Defining send-mail function#####
function sendmail($subject, $data)
{
$to = "mperry.it@gmail.com"
$from = "mperry.it@gmail.com"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$Password = Get-Content "cred.txt" | ConvertTo-SecureString -key $getkey
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer,$SMTPPort);
$smtp.EnableSsl = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($to, $Password);
$smtp.Send($to, $from, $subject, $data);
}
# Formating Date for day-month-year
$date = Get-Date -Uformat "%d-%m-%Y"
#Mounting \\freenas.domain.local\veeam-backup as drive letter :
New-PSDrive -Name "H" -PSProvider FileSystem -Root "\\freenas.domain.local\veeam-backup\"
#Creating new directory with current date
New-Item -Name "backup_$date" -Path "H:\" -ItemType Directory
#Copying all veeam backup files to NAS in current date directory
Copy-Item -Path "D:\vm-backup\*.vbk" -Destination "H:\backup_$date"
#Remove directories and their files older than 3 days
#Get-ItemProperty -Path "P:\backup $date" | where-object {$_.LastWriteTime -lt ($date).AddDays(-3)} | Remove-Item -Force -Recurse
$Now = Get-Date
$Days = "3"
$TargetFolder = "H:\"
cd $TargetFolder
$LastWrite = $Now.AddDays(-$Days)
$Folders = get-childitem -path $TargetFolder |
Where {$_.psIsContainer -eq $true} |
Where {$_.LastWriteTime -le "$LastWrite"}
foreach ($Folder in $Folders){
write-host "Deleting $Folder" -foregroundcolor "Red"
Remove-Item $Folder -recurse -Confirm:$false
}
cd C:
#Unmount drive P:
Remove-PSDrive -Name "H"
#Successful backup mail
$subject = "Veeam backup copy successful"
$data = "Copying VMs on freenas is successfull on $day with an $up"
}
Catch {
#Unsuccessful backup mail
$subject = "Veeam backup copy failed"
$data = $_.Exception.Message
}
Finally {
sendmail $subject $data
}
Я пытался переместить свои функции за пределы попытки и поймать внутри себя некоторые функции за пределами некоторых внутри. Он всегда работает в ручном режиме, но не в планировщике задач.
Но помните, что скрипт выполняет копирование, но не отправляет электронное письмо.