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

Posted on 2014-08-01
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: - 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
    LVL 40

    Expert Comment

    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 -To -Subject $line -SmtpServer

    Open in new window


    Author Comment

    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

    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

    LVL 38

    Expert Comment

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

    Author Comment

    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

    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 -To -Subject $line -SmtpServer -Credential $Cred

    Open in new window


    Author Closing Comment

    Perfect , the script work superbly! Thank you.

    Author Comment

    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

    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 :

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Enabling OSINT in Activity Based Intelligence

    Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

    Why would I want to create a function for tracking messages? I am glad you asked. As with most monotonous/routine tasks, human error tends to creep in after doing the same task over and over again. By creating a function, you load the function once…
    Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
    To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…
    In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

    779 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

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now