How to Use PowerShell to Monitor Text Files and Trigger Alerts for IT Professionals

In today’s IT landscape, automation is key to efficiently managing and monitoring systems. PowerShell, with its powerful scripting capabilities, is a go-to tool for IT professionals and Managed Service Providers (MSPs) looking to streamline their workflows. One common task is monitoring text files for specific content—whether it’s to track logs, detect errors, or alert on critical information.

The PowerShell script we’re exploring today serves this very purpose: it alerts you when a specified text is found in a text file, making it an invaluable tool for those responsible for maintaining the health and security of IT systems.

Background

Text files are often used in IT environments to log activities, store configuration data, or hold critical information. Monitoring these files for specific keywords or phrases is crucial for various reasons, such as detecting security breaches, ensuring compliance, or identifying system failures.

Traditionally, IT professionals might manually inspect these files or use complex software solutions to monitor them. However, with PowerShell, you can automate this process with a simple yet effective script. This script is particularly beneficial for MSPs who manage multiple clients and need a reliable way to monitor text files across different environments.

The Script:

#Requires -Version 4

<#
.SYNOPSIS
    Alert when the specified text is found in a text file.
.DESCRIPTION
    Alert when the specified text is found in a text file.
.EXAMPLE
    (No Parameters)
    ## EXAMPLE OUTPUT WITHOUT PARAMS ##

PARAMETER: -Path "C:\ReplaceMe\WithPath\To\Text.txt"
    File path to the text file you would like to monitor.

PARAMETER: -TextToMatch "ReplaceMeWithTextToFind"
   Text to alert on when found.

.EXAMPLE
    -Path "C:\Test-FileMonitor.txt" -TextToMatch "bat"
    
    [Alert] Found Text!

.EXAMPLE
    -Path "C:\Test-FileMonitor.txt" -TextToMatch "man" -MatchOnlyOnWholeWord
    
    Text Not Found!

PARAMETER: -MatchOnlyOnWholeWord
    Alert only when your given 'Text To Match' is not contained in another word.

PARAMETER: -CaseSensitive
    Alert only when the casing of your specified 'Text To Match' is identical; for example, alert on 'BAT' but not 'bat'.
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2012
    Release Notes: Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://ninjastage2.wpengine.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[CmdletBinding()]
param (
    [Parameter()]
    [String]$Path,
    [Parameter()]
    [String]$TextToMatch,
    [Parameter()]
    [Switch]$WholeWordOnly = [System.Convert]::ToBoolean($env:matchOnlyOnWholeWord),
    [Parameter()]
    [Switch]$CaseSensitive = [System.Convert]::ToBoolean($env:caseSensitive)
)

begin {
    # Set Dynamic Script Variables
    if($env:textToMatch -and $env:textToMatch -notlike "null"){
        $TextToMatch = $env:textToMatch
    }
    if($env:textFilePath -and $env:textFilePath -notlike "null"){
        $Path = $env:textFilePath
    }

    # Check for local administrator rights.
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    # Check that a path was given and if not error out.
    if (-not $Path) {
        Write-Host "[Error] A filepath is required!"
        exit 1
    }

    # If not given text to match error out.
    if (-not $TextToMatch){
        Write-Host "[Error] Text to match is required!"
        exit 1
    }

    # Error out if script is running without local administrator rights.
    if (-not (Test-IsElevated)) {
        Write-Host "[Error] Access Denied. Please run with Administrator privileges."
        exit 1
    }

    # Check that the path given exists.
    if (-not (Test-Path -Path $Path)) {
        Write-Host "[Error] File does not exist!"
        exit 1
    }

    # Check that we're given a file and not a folder.
    $File = Get-Item -Path $Path
    if ($File.PSIsContainer) {
        Write-Host "[Error] Please provide a file path, not a directory."
        exit 1
    }

    $ExitCode = 0
}
process {
    # Check if we were given a binary file and if so error out.
    $ByteCount = 1024
    $ByteArray = Get-Content -Path $Path -Encoding Byte -TotalCount $ByteCount
    if ($ByteArray -contains 0 ) {
        Write-Host "[Error] This script does not support searching binary files!"
        exit 1
    }

    # Retrieve file contents.
    $File = Get-Content -Path $Path

    # If file is empty error out.
    if (-not $File) {
        Write-Host "[Error] reading file, file is either empty or you do not have permission to read it."
        exit 1
    }

    # Scan through each-line checking for our text.
    $File | ForEach-Object {
        # Based on the parameters given match the text.  
        if (-not $CaseSensitive -and -not $WholeWordOnly -and $_ -like "*$TextToMatch*") {
            $Match = $True
        }

        if ($CaseSensitive -and -not $WholeWordOnly -and $_ -clike "*$TextToMatch*") {
            $Match = $True
        }

        if ($WholeWordOnly -and -not $CaseSensitive -and $_ -match "\b$TextToMatch\b") {
            $Match = $True
        }

        if ($WholeWordOnly -and $CaseSensitive -and $_ -cmatch "\b$TextToMatch\b") {
            $Match = $True
        }
    }

    # If our text matched alert.
    if ($Match) {
        Write-Host "[Alert] Found Text!"
    }
    else {
        Write-Host "Text Not Found!"
    }

    exit $ExitCode
}
end {
    
    
    
}

 

Detailed Breakdown

The provided script is designed to monitor a text file for specific content and alert the user when the text is found. Here’s a step-by-step breakdown of how the script works:

1. Parameters Setup:

  • The script begins by defining parameters such as -Path (the file path to the text file you want to monitor) and -TextToMatch (the text you want to find). Optional parameters include -WholeWordOnly to ensure the text is matched only when it appears as a whole word, and -CaseSensitive to differentiate between cases.

2. Environment Variables:

  • The script checks if environment variables are set for textToMatch and textFilePath. If they are, these values override the parameters provided by the user.

3. Privilege and Path Validation:

  • The script includes a function to check if it’s running with administrative privileges, which is necessary for accessing certain files or system paths. It also verifies that the provided path exists and points to a valid file rather than a directory.

4. File Content Retrieval:

  • The script reads the contents of the specified file. If the file is empty or the user lacks permission to read it, the script will error out, preventing further execution.

5. Text Matching Logic:

  • The script iterates through each line of the file, applying the specified text-matching criteria. It checks whether the -CaseSensitive or -WholeWordOnly options are enabled and adjusts the matching logic accordingly. If the text is found, the script alerts the user by printing [Alert] Found Text!; otherwise, it prints Text Not Found!.

6. Error Handling:

  • Throughout its execution, the script includes robust error handling to ensure it gracefully exits with appropriate error messages if any issues arise, such as missing parameters, lack of privileges, or invalid file paths.

This script offers a powerful yet straightforward way to monitor text files, making it an essential tool in the IT professional’s toolkit.

Potential Use Cases

Imagine an IT professional responsible for monitoring security logs across multiple servers. They need to detect specific error messages or unauthorized access attempts as soon as they occur.

By deploying this script, they can automate the process of scanning these log files for critical keywords, such as “unauthorized access” or “error 503”. Whenever these keywords are found, the script immediately alerts them, allowing for rapid response to potential security threats. This proactive approach enhances the security posture of the organization and reduces the risk of overlooking critical issues.

Comparisons

Compared to other methods, such as using third-party log management software or manually inspecting logs, this PowerShell script offers a lightweight and customizable solution. While third-party tools might provide more features, they often come with a cost and require additional configuration.

On the other hand, manual inspection is time-consuming and prone to human error. This script strikes a balance by providing an automated, cost-effective solution that integrates seamlessly into existing workflows.

FAQs

1. Can this script be used to monitor multiple files simultaneously?

No, this script is designed to monitor a single file at a time. However, you can modify the script or run it in parallel for multiple files.

2. What happens if the file being monitored is updated after the script starts running?

The script reads the file’s contents at the time of execution. If the file is updated after the script starts, those changes will not be detected unless the script is rerun.

3. Is it possible to log the alerts to a file instead of displaying them on the console?

Yes, you can modify the script to log alerts to a file by replacing Write-Host with Add-Content or Out-File.

Implications

Using this script to monitor critical files can have significant implications for IT security. By automating the detection of key phrases or error messages, IT professionals can respond more quickly to potential issues, reducing downtime and mitigating security risks.

However, it’s important to remember that this script operates within the confines of the specified text file and is only as effective as the keywords it is configured to monitor. If used correctly, it can be a powerful tool in the broader strategy of IT monitoring and incident response.

Recommendations

When using this script, it’s best to follow these practices:

  • Test in a Controlled Environment: Before deploying the script in a production environment, test it in a controlled setting to ensure it behaves as expected.
  • Regularly Update Keywords: Review and update the keywords you’re monitoring to ensure they align with evolving threats and operational requirements.
  • Integrate with Other Tools: Consider integrating the script with other monitoring tools or alert systems to create a more comprehensive monitoring solution.

Final Thoughts

For IT professionals, especially those managing multiple environments, automation is crucial. This PowerShell script offers a simple yet effective way to monitor text files for critical information, allowing for prompt responses to potential issues.

While this script is a powerful tool on its own, it’s worth noting that comprehensive IT management solutions like NinjaOne can further enhance your ability to monitor, manage, and secure your systems. By combining such scripts with a broader IT management platform, you can ensure your organization’s IT infrastructure remains robust and resilient.

Add a Comment

Your email address will not be published. Required fields are marked *

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).