我正在开发一个PowerShell脚本,供帮助台在将userhome文件夹从服务器迁移到NAS设备时使用。帮助台用户将用户名输入“userhomelist.txt”文件。
我的问题是我无法让脚本附加所有日志文件。只有最后一个日志文件附加到电子邮件中。我想我需要使用一个字符串作为多个附件,但我一直认为还有另一种方法。
#----- STEP #1 retrieve contents of input file ---#
$INPUTFILEPATH = 'c:\temp\userhomelist.txt'
#----- read input file contents ----#
$inputdata = Get-Content $INPUTFILEPATH
#----- Top section of email body ----#
$msgreport = new-object Net.Mail.MailMessage
$msgreport = "To view log files, go to directory where this PowerShell Script was run from. `r"
$msgreport = $msgreport + "`r`n"
#read in each username
foreach ($username in $inputdata)
{
#----- STEP #2 robocopy files from \\server to \\nasdevice location ----#
Start-Process -FilePath robocopy -ArgumentList "\\server\userhomes\$username \\nasdevice\userhomes\$username /mir /sec /r:1 /w:1 /tee /NP /Z /log+:userhome-move-$username.log"
$file = "c:\temp\userhome\userhome-move-$username.log"
$msgreport = $msgreport + "$username robocopy has been completed." + "`n"
##----- STEP #3 change file and directory ownership to user ----#
Start-Process -FilePath subinacl -ArgumentList "/subdirectories \\nasdevice\userhomes\$username\*.* /setowner=$username"
$msgreport = $msgreport + "$username file and directory ownership changes have been completed." + "`n"
$msgreport = $msgreport + "`r`n"
}
#----- Email Results ----#
$SmtpClient = new-object system.net.mail.smtpClient
$MailMessage = New-Object system.net.mail.mailmessage
$SmtpServer = "emailserver.business.com"
$SmtpClient.host = $SmtpServer
$MailMessage.From = "userhome-migration@business.com"
$MailMessage.To.add("helpdeskn@business.com")
$MailMessage.Subject = "User migrations"
$MailMessage.IsBodyHtml = 0
$MailMessage.Body = $msgreport
$MailMessage.Attachments.Add($file)
$SmtpClient.Send($MailMessage)
答案 0 :(得分:10)
如果您在powershell v2或v3中,我建议使用send-mailmessage
cmdlet。
它有一个-attachments
参数,可以接受字符串数组(string[]
)。
您可以在$file
用户循环之前更改变量$file = @()
,将其声明为foreach
。
在foreach内部做:
$file += "c:\temp\userhome\userhome-move-$username.log"
将$msgreport
更改为[string]
类型
然后使用send-mailmessage
cmdlet执行:
send-mailmessage -SmtpServer "emailserver.business.com" `
-From "userhome-migration@business.com" -to "helpdeskn@business.com" `
-Subject "User migrations" -BodyAsHtml -Body $msgreport -Attachments $file