[Last Call] Learn how to a build a cloud-first strategyRegister Now


PoweShell Get-Content  Script to read a text file comparing data and time

Posted on 2014-08-01
Medium Priority
Last Modified: 2014-08-02
I have this powershell command that read a text file for Quickbook Web Connector log and search for a specific text "No data to exchange for the application"  :

Output command:

PS C:\Users\ch> Get-Content C:\Users\ch\Documents\test.txt | select-string "No data to exchange for the application"| Se
lect-Object -last 1

20140801.15:14:14 UTC    : QBWebConnector.WebServiceManager.DoUpdateSelected() : No data to exchange for the
application:  www.abc.com - QB Financial Web Connector
I need to create a script that run every 3 Hours and compare the date and time if the last result was 3 Hours from the current time and send an email like an alert.

For Example:

The script need to check for the last result " See output above"  date and time "20140801.15:14:14 UTC....."  with the current time (when the script run) 20140801.18:14:14 and if it's more than > 3 Hours send an email with the results with the output .

Let me know if this is possible.

Thank you.
Question by:demichel
  • 4
  • 4
LVL 40

Expert Comment

ID: 40235535
Try this..
$line = Get-Content Get-Content C:\Users\ch\Documents\test.txt | select-string "No data to exchange for the application"| Select-Object -last 1

$date = [datetime]::ParseExact("$(($line -split "UTC")[0].Trim())", "yyyyMMdd.HH:mm:ss", $null)

If ((((Get-Date).ToUniversalTime()) - $date).Hours -ge 3){
Send-MailMessage -From From.domain.com -To To@domain.com -Subject $line -SmtpServer smtp.domain.com

Open in new window


Author Comment

ID: 40235552
I'm getting this error :

PS C:\Users\ch\Documents> .\alert.ps1
Get-Content : A positional parameter cannot be found that accepts argument 'C:\Users\ch\Documents\test.txt'.
At C:\Users\ch\Documents\alert.ps1:1 char:9
+ $line = Get-Content Get-Content C:\Users\ch\Documents\test.txt | select-string " ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-Content], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetContentCommand
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At C:\Users\ch\Documents\alert.ps1:2 char:35
+ $date = [datetime]::ParseExact("$(($line -split "UTC")[0].Trim())", "yyyyMMdd.HH ...
+                                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException
Cannot find an overload for "op_Subtraction" and the argument count: "2".
At C:\Users\ch\Documents\alert.ps1:3 char:5
+ If ((((Get-Date).ToUniversalTime()) - $date).Hours -ge 3){Send-MailMessage -From ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest
LVL 40

Expert Comment

ID: 40235560
There is a typo in first line..
$line = Get-Content C:\Users\ch\Documents\test.txt | select-string "No data to exchange for the application"| Select-Object -last 1

Open in new window

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

LVL 41

Expert Comment

ID: 40235575
Was posting, but then saw Subsun already had about the same code... :)

Author Comment

ID: 40235576
Now I'm getting smtp authentication error can you send me the complete code to send email from smtp server with authentication ?

Send-MailMessage : Mailbox unavailable. The server response was: must be authenticated
At C:\Users\ch\Documents\alert.ps1:3 char:59
+ If ((((Get-Date).ToUniversalTime()) - $date).Hours -ge 3){Send-MailMessage -From ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpFailedRecipientException
    + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage
LVL 40

Accepted Solution

Subsun earned 1760 total points
ID: 40235580
Try using Credential  parameter with Send-MailMessage
$Pwd = ConvertTo-SecureString "YourPassword" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential ("Yourusername", $Pwd)

Send-MailMessage -From From.domain.com -To To@domain.com -Subject $line -SmtpServer smtp.domain.com -Credential $Cred

Open in new window


Author Closing Comment

ID: 40235592
Perfect , the script work superbly! Thank you.

Author Comment

ID: 40236253
It is possible to change to check only for the last 3 hours ? so the range of 3 hours time frame < 3 ? and include after send the email to run a batch file ?

Let me know

thank you,
LVL 40

Expert Comment

ID: 40236514
In the code -ge 3 means... if the date difference is greater than or equal to 3. You can change this Comparison Operator to  -le 3 (Less than or equal).

Ref : http://ss64.com/ps/syntax-compare.html

Featured Post

NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This script can help you clean up your user profile database by comparing profiles to Active Directory users in a particular OU, and removing the profiles that don't match.
Windows 10 came with  a lot of built in applications, Some organisations leave them there, some will control them using GPO's. This Article is useful for those who do not want to have any applications in their image (example:me).
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Screencast - Getting to Know the Pipeline

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question