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-文件与Send-MailMessage-附件一起正确使用,以实现我正在尝试做的事情。

哈里奇

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

#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();

来源

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章