Powershell 压缩文件并发送电子邮件

Powershell 压缩文件并发送电子邮件

Powershell 压缩文件并发送电子邮件。

我想用 7zip 压缩备份文件并将其作为电子邮件发送。下面是我到目前为止所做的操作,它将读取文本文件并将其作为电子邮件发送。相反,我想将所有文件作为电子邮件发送。

param (
    [Parameter(Position=0,Mandatory=$true)] [string] $scriptPath

    )

$smtpSvr = "google.com"
$From = "[email protected]"
$To = "[email protected]"
$Subject = "Check log files attached"

[string]$messagebody = ""

$logs = Get-Content $Path\*.txt

foreach ($log in $logs )
{
    $messagebody = $messagebody + $log + "`r`n"
}

$smtp = New-Object Net.Mail.SmtpClient($smtpSvr)
$smtp.Send($From,$To,$Subject,$messagebody)

答案1

您可以使用Send-MailMessagecmdlet 吗?使用Eld 的 zip 函数在堆栈溢出和您声明的变量......

function ZipFiles( $zipfilename, $sourcedir )
{
   Add-Type -Assembly System.IO.Compression.FileSystem
   $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
   [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir, $zipfilename, $compressionLevel, $false)
}

ZipFiles "c:\logfiles.zip" $scriptPath
Send-MailMessage -SmtpServer $smtpSvr -From $From -To $To -Subject $Subject -Attachments "C:\logfiles.zip" -Body $messagebody

相关内容