问题
This script will be sending email to myself if more than 2 lines (3rd lines onwards). I tried on below script but not managed to get any email notification. SMTP server is working fine and no issue. May I know what problem with my code?
Tools:
- Using powershell v2.0
- Using .Net 4
- Window Server 2008
$Output = ".\Name.txt" If (Get-Content -Path $Output | Where-Object {$_.Count -gt 2}) { $MailArgs = @{ 'To' = "myemail@company.com" 'From' = "from@company.com" 'Subject' = "Pending. " 'Attachments' = $Output 'Body' = "Please close it" 'SmtpServer' = "exchangeserver.com" } Send-MailMessage @MailArgs }
Example of Output File will send email
| Name | PassportNo | DOB | |
+------+------------+------------+--------------------------------------+
| A | IDN7897 | 29-08-1980 | << once got this row will send email |
| B | ICN5877 | 14-08-1955 | |
| C | OIY7941 | 01-08-1902 | |
+------+------------+------------+--------------------------------------+
回答1:
As commented, your If test is wrong.
Using If (Get-Content -Path $Output | Where-Object {$_.Count -gt 2})
you are piping each single line from the file and test if the .Count property on that single line is greater than 2 (which of course is never the case)
Change the If into
If ((Get-Content -Path $Output).Count -gt 2)
so the .Count property will give you the total number of lines in the file.
来源:https://stackoverflow.com/questions/58660017/send-email-if-get-content-of-file-more-than-2-line