Powershell腳本

Powershell腳本

我正在嘗試編寫一個 PowerShell 腳本,它將 C:\Reports\ 每個子資料夾中的所有文件作為附件一起透過電子郵件發送。例如,如果子資料夾是包含a.txt、b.xml 和c.jpg 的C:\Reports\ABC,以及包含d.txt、e.xml 和f.pdf 的C:\Reports\DEF,則程式碼應透過電子郵件發送一封電子郵件中包含 .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();

來源

相關內容