Friday, 20 December 2024

Search for an IP Address in the Last 7 Days of Windows Security Event Logs

This PowerShell script allows you to filter Windows Security event logs for a specific IP address, focusing on events from the past 7 days. The results are saved to a CSV file for further analysis.







The Script

# Define the IP address and output CSV file path $ipaddress = "10.1.1.1" $outputFile = "C:\SecurityEvents_Last7Days.csv" # Define the start date (7 days ago) $startDate = (Get-Date).AddDays(-7) # Extract the events from the last 7 days and export to CSV Get-WinEvent -LogName Security -FilterXPath "*[EventData[Data[@Name='IpAddress']='$ipaddress']]" | Where-Object { $_.TimeCreated -ge $startDate } | Select-Object TimeCreated, Id, Message | Export-Csv -Path $outputFile -NoTypeInformation -Encoding UTF8 # Notify user of completion Write-Output "Events from the last 7 days successfully exported to $outputFile"

Key Features

  1. Filters by IP Address: Searches for events where the IP address matches the specified value.
  2. Time Range: Limits results to events that occurred in the last 7 days using the TimeCreated property.
  3. CSV Output: Saves event details (timestamp, ID, and message) to a specified CSV file.

How to Use It

  1. Replace 10.1.1.1 with the target IP address.
  2. Save the script to a .ps1 file or run it directly in PowerShell with administrator privileges.
  3. Locate the output file (C:\SecurityEvents_Last7Days.csv) for review.

Script Workflow

  1. Input Definition: The $ipaddress variable holds the IP address, and $outputFile specifies the CSV file location.
  2. Time Range Setup: $startDate is calculated as 7 days prior to the current date.
  3. Event Filtering: Get-WinEvent retrieves log entries matching the IP address. Where-Object ensures only events from the past 7 days are included.
  4. Data Export: Selected details are saved to the CSV file for analysis.

Practical Applications

  • Security Monitoring: Quickly identify events tied to suspicious IP activity.
  • Incident Investigation: Focus on recent logs for faster issue resolution.
  • Data Analysis: Exported CSV files can be reviewed in Excel or other tools.

Conclusion

This script is a concise, efficient way to analyze recent security events related to a specific IP address. Adjust the IP and time range as needed for your specific use case, and use the exported data to inform your network security actions.

No comments:

Post a Comment