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.
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
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.
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";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.