Powershell 脚本

Powershell 脚本

我正在尝试编写一个 PowerShell 脚本,该脚本会将 C:\Reports\ 中每个子文件夹中的所有文件作为附件一起发送到一封电子邮件中。例如,如果子文件夹为 C:\Reports\ABC,其中包含 a.txt、b.xml 和 c.jpg,而 C:\Reports\DEF 中包含 d.txt、e.xml 和 f.pdf,则代码应在一封电子邮件中发送 a.txt、b.xml 和 c.jpg,在另一封电子邮件中发送 d.txt、e.xml 和 f.pdf。我编写了以下代码:-

$Directory=Get-ChildItem "C:\Reports\" -Directory 
$Cred = Get-Credential 
Foreach($d in $Directory) { 
Write-Host "Working on directory $($d.FullName)..." 
$files=Get-ChildItem -Path "$($d.FullName)"
cd $d.Fullname  
Send-MailMessage -From "[email protected]" -To "[email protected]" -Subject "test" -SmtpServer "smtp.gmail.com" -Port "587" -Attachments $files -BodyAsHtml "test msg" -Credential $Cred -UseSsl
} 

但是这似乎只附加了每个子文件夹中的最后一个文件,然后转到下一个文件夹并发送电子邮件。我想知道如何正确使用 Get-ChildItem - File 和 Send-MailMessage - Attachments 来实现我想要做的事情。

答案1

以下是一些(未经测试的)代码:

#Connection Details
$username="john"
$password="password"
$smtpServer = "mail.server.local"
$msg = new-object Net.Mail.MailMessage

#Change port number for SSL to 587
$smtp = New-Object Net.Mail.SmtpClient($SmtpServer, 25) 

#Uncomment Next line for SSL  
#$smtp.EnableSsl = $true

$smtp.Credentials = New-Object System.Net.NetworkCredential( $username, $password )

#From Address
$msg.From = "[email protected]"
#To Address, Copy the below line for multiple recipients
$msg.To.Add("[email protected]")

#Message Body
$msg.Body="Please See Attached Files"

#Message Subject
$msg.Subject = "Email with Multiple Attachments"

#your file location
$files=Get-ChildItem "C:\Reports\"

Foreach($file in $files)
{
Write-Host "Attaching File :- " $file
$attachment = new-object Net.Mail.Attachment -ArgumentList $file.FullName
$msg.Attachments.Add($attachment)
}

$smtp.Send($msg)
$attachment.Dispose();
$msg.Dispose();

来源

相关内容