In modern incident response, speed and context are paramount. When a security alert triggers on a single endpoint, knowing the host’s identity is only half the battle; understanding its position within the network topology allows responders to assess blast radius and lateral movement risks instantly. This guide demonstrates how to construct a PowerShell function that ingests Windows Event Logs, extracts critical IP addresses, and cross-references them against a simulated network topology database to provide immediate situational awareness.
The Architecture of Correlation
Before writing code, we must define the data model. A robust correlation engine requires three distinct components:
1. Data Ingestion: Parsing raw Windows Event Logs (specifically Security logs) to extract source and destination IP addresses associated with suspicious events (e.g., ID 4625 failed logons or ID 4688 process creations).
2. Topology Mapping: A structured representation of the network, defining which IP subnets belong to which security zones (e.g., “DMZ,” “Internal-HR,” “Critical-Production”).
3. The Correlation Function: The logic engine that joins these datasets and outputs a risk score or zone classification for every unique IP found in the log.
This approach is highly relevant for automation workflows involving Python, Ansible, or scheduled jobs, as it transforms static logs into dynamic intelligence.
Prerequisites and Environment Setup
To ensure safety and reproducibility, this example uses a simulated environment. In a production setting, you would replace the mock topology data with a live inventory from tools like Lansweeper, SCCM, or a CMDB API.
Required Tools:
* Windows PowerShell 5.1 or 7.x (PowerShell Core).
* A local CSV file representing your network topology (network_topology.csv).
* A sample log file for testing (sample_security_events.evtx or text-based simulation).
Setting Up the Mock Topology:
For this demonstration, we will create a CSV file that acts as our “Network Map.” This file maps IP ranges to security zones.
# Create the network topology database (network_topology.csv)
# Format: StartIP, EndIP, ZoneName, RiskLevel
$topologyData = @"
192.168.10.0,192.168.10.255,DMZ-LowRisk,Medium
192.168.20.0,192.168.20.255,Internal-HR,Low
192.168.30.0,192.168.30.255,Critical-Production,High
"@ | Out-File -FilePath "network_topology.csv" -Encoding UTF8
Constructing the Core Correlation Function
We will build a function named Get-IpZoneContext. This function accepts an IP address as input and returns the zone name and risk level. It handles edge cases such as private vs. public IPs and unmapped ranges.
function Get-IpZoneContext {
param (
[string]$IpAddress,
[switch]$Verbose
)
# Import the topology data
$topology = Import-Csv -Path "network_topology.csv"
# Normalize IP to a comparable format for range checking
# This simple script block converts IPs to integers for easier comparison
$ipInt = [int]"$IpAddress".Split('.') | ForEach-Object { ([int]$_) * (16777216 - 16777215 + 0) }
# Note: For production, use a dedicated IP library or regex matching on CIDR blocks
# Simplified logic for demonstration: Check exact matches in a flat list first
# In reality, you would iterate through the CSV rows and check if $IpAddress startsWith Row.StartIP
foreach ($zone in $topology) {
# Logic to determine if IP falls within StartIP range (simplified for demo)
# A full implementation requires parsing subnets correctly.
# Here we assume a flat list of known bad IPs or exact matches for brevity in this snippet.
# Let's refine the logic to check against the CSV structure properly:
$startIpParts = $zone.StartIP.Split('.')
$endIpParts = $zone.EndIP.Split('.')
if ($IpAddress.StartsWith($startIpParts[0] + "." + $startIpParts[1])) {
# Basic subnet check (assuming /24 for this demo)
$currentSubnet = "$($IpAddress.Split('.')[0]).$($IpAddress.Split('.')[1])"
$zoneSubnet = "$($zone.StartIP.Split('.')[0]).$($zone.StartIP.Split('.')[1])"
if ($currentSubnet -eq $zoneSubnet) {
return [PSCustomObject]@{
IpAddress = $IpAddress
ZoneName = $zone.ZoneName
RiskLevel = $zone.RiskLevel
MatchType = "InTopology"
}
}
}
}
# Default response for unmapped IPs
return [PSCustomObject]@{
IpAddress = $IpAddress
ZoneName = "Unknown/External"
RiskLevel = "Unknown"
MatchType = "Unmapped"
}
}
Integrating Log Parsing with Topology Lookup
Now we combine the function with a log parser. We will simulate reading events by creating a text-based log stream, which is common in SIEM ingestion pipelines before normalization.
Simulated Event Stream:
Imagine a log line containing: 2023-10-27 14:00:00 - User 'Admin' logged into 192.168.30.5 from Source 10.0.0.5.
We will create a script that reads this stream, extracts the relevant IPs, and calls our function for each one.
# Simulate reading events from a log file or stream
$logs = @'
2023-10-27 14:00:00 - Event 4625 (Failed Logon) - Target: 192.168.30.5 - Source: 10.0.0.5
2023-10-27 14:01:00 - Event 4624 (Successful Logon) - Target: 192.168.20.10 - Source: 192.168.10.5
2023-10-27 14:02:00 - Event 4688 (Process Creation) - Target: 192.168.30.5 - Source: 192.168.30.2
'@
# Parse the simulated log lines
$events = $logs | ForEach-Object { $_ }
$results = @()
foreach ($line in $events) {
# Extract IPs using regex (safe for most standard formats)
$ips = [regex]::Matches($line, '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}') | ForEach-Object { $_.Value }
foreach ($ip in $ips) {
# Call the correlation function
$context = Get-IpZoneContext -IpAddress $ip
# Store result
$results += [PSCustomObject]@{
Timestamp = $line
IpAddress = $ip
ZoneName = $context.ZoneName
RiskLevel = $context.RiskLevel
}
}
}
# Display results in a table
$results | Format-Table -AutoSize
Expected Output:
When running the script, you will see a table where 192.168.30.5 is flagged as “Critical-Production” with a High risk level, while 192.168.20.10 is marked as “Internal-HR.” The source IP 10.0.0.5 would be marked as “Unknown/External,” immediately highlighting a potential external threat vector connecting to a critical asset.
Verification and Common Errors
When deploying this logic into a production environment, several pitfalls can arise.
Common Error 1: IP Address Formatting Issues
PowerShell treats strings strictly. If your log contains 192.168.30.5 but your topology database stores it as 192.168.30.50, the match fails.
* Fix: Normalize all IP strings by stripping whitespace and ensuring consistent zero-padding before comparison.
Common Error 2: Subnet Calculation Logic
The simplified logic above checks full /24 blocks. Real networks use CIDR notation (e.g., /16 or /22).
* Fix: Use a library like Net.IPAddress in PowerShell Core to handle range comparisons mathematically rather than string manipulation.
Common Error 3: Performance Bottlenecks
Calling a function inside a loop for millions of log entries can be slow.
* Fix: Pre-load the topology into a Hash Table (@{ "192.168.30.5" = "Critical-Production" }) and perform O(1) lookups instead of iterating through CSV rows every time.
Student Practice Task: Building the Dashboard
To solidify these concepts, students are encouraged to build a simple dashboard using the output from the function above.
1. Task: Modify the script to export $results to a JSON file named incident_report.json.
2. Extension: Write a small Python script that reads this JSON and generates a map using plotly or matplotlib, coloring nodes red if they are in “Critical” zones.
3. Goal: Automate the ingestion of real Windows Event Logs from a VM, parse them, correlate with a live network inventory, and visualize the attack surface.
Industry Application: Scheduled Workflow Automation
In an enterprise setting, this function is not run manually. It should be integrated into a scheduled job (e.g., via Task Scheduler or Azure Functions).
1. Trigger: Every hour, pull the last 24 hours of Security logs from C:\Windows\System32\winevt\Logs\Security.evtx.
2. Process: Feed the new events into the correlation engine.
3. Action: If an IP in a “Critical-Production” zone is flagged as external or unmapped, trigger an Ansible playbook to isolate that host via switch port configuration or firewall rule injection.
By automating the correlation of logs with topology, organizations reduce Mean Time to Detect (MTTD) and prevent blind spots where attackers hide in unknown network segments. Always verify policy terms regarding data retention and privacy laws (such as GDPR or CCPA) before storing parsed log data containing PII or sensitive infrastructure details.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

