[英]Powershell script to send email with list of files in a folder - formatting issue
thank you for taking the time to look at my question.谢谢你花时间看我的问题。
I have a Powershell script that checks for files in a folder and sends an email if any files are older than 3 hours.我有一个 Powershell 脚本,用于检查文件夹中的文件,如果任何文件超过 3 小时,则发送电子邮件。
The only problem is, I can't seem to get the formatting right when trying to output into the body of an email.唯一的问题是,在尝试输出到电子邮件正文时,我似乎无法正确设置格式。
Here is the script:这是脚本:
$emailSmtpServer = "emailserver.com"
$emailSmtpUser = "email@domain.com"
$emailSmtpPass = "password"
$emailSmtpServerPort = "587"
$emailFrom = "email@domain.com"
$emailTo = "email@domain.com"
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$limit = (Get-Date).AddHours(-3)
$path = "C:\folder"
$files = (Get-ChildItem -Path $path -Recurse | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit })
#$files | ft
if ($files -ne $NULL)
{
$emailMessage = New-Object System.Net.Mail.MailMessage( $emailFrom , $emailTo )
$emailMessage.Subject = "list of files"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = "Here is a list of the files: <p> $files"
$SMTPClient.Send( $emailMessage )
}
The line that is commented out (#$files | ft) would format the output to look like this被注释掉的行 (#$files | ft) 会将输出格式化为如下所示
PS C:\test> .\filecheck.ps1
Directory: C:\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 4/20/2015 7:43 PM 1430 file1.txt
-a--- 4/20/2015 7:44 PM 1430 file2.ps1
-a--- 4/19/2015 11:29 PM 3551 file3.txt
-a--- 4/19/2015 11:28 PM 2078 file4.txt
I don't necessarily need the "Mode" or "Length" in the list, Just a list of the creation date and the filename would be fine for my purposes.我不一定需要列表中的“模式”或“长度”,只要列出创建日期和文件名就可以了。 That table gets output to the console, but the body of the email is coming out like this:
该表将输出到控制台,但电子邮件的正文如下所示:
file1.txt file2.ps1 file3.txt file4.txt
This makes it difficult to work through the list of files, especially if there are a lot.这使得处理文件列表变得困难,尤其是在文件很多的情况下。
I am not great at powershell yet, but I have tried everything I could find, I know it has to be something simple.我还不太擅长 powershell,但我已经尝试了所有我能找到的东西,我知道它必须很简单。
I appreciate any help.我很感激任何帮助。
This is a possible way: get all your files in an array这是一种可能的方法:将所有文件放在一个数组中
$files = @(Get-ChildItem -Path $path -Recurse | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit })
Then create the body of your email cycling through the array of files and writing a line for each one with the details you need, for example然后创建您的电子邮件正文,循环浏览文件数组,并为每个文件写一行,其中包含您需要的详细信息,例如
$mailBody = "";
foreach ($file in $files) {
$mailBody += "file name: $($file.Name); last write time: $($file.LastWriteTime)`r`n";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.