Skip to content

Instantly share code, notes, and snippets.

@asheroto
Last active July 7, 2024 00:40
Show Gist options
  • Save asheroto/0a6eddbf5b53c8d5caac70ef35a461f1 to your computer and use it in GitHub Desktop.
Save asheroto/0a6eddbf5b53c8d5caac70ef35a461f1 to your computer and use it in GitHub Desktop.
PowerShell script to extract IP addressees from a file and count the number of occurrences of each IP address.

Extract IP Addresses and Count Occurrences

PowerShell script to extract IP addressees from a file (i.e. log file) and count the number of occurrences of each IP address.

  • Detects IPv4 only
  • IP address matching is done through regex
  • Not perfect but a quick an easy approach

Usage

Function name:

ExtractIPaddressesAndCount

Required Parameters:

Parameter Description
-InputFile Input file such as a log file that contains IP addresses
-OutputFile File to write with the list of IPs and occurrences

Example:

Import-Module ./Extract-IP-Addresses-and-Count.ps1
ExtractIPaddressesAndCount -InputFile "C:\Downloads\access.log" -OutputFile "C:\Downloads\Output.log"

Sample Output File

sample output

function ExtractIPaddressesAndCount {
[CmdletBinding()]
param(
[Parameter(Position = 0, mandatory = $true)]
[string] $InputFile,
[Parameter(Position = 1, mandatory = $true)]
[string] $OutputFile
)
If (-Not(Test-Path -Path $InputFile -PathType Leaf)) {
Write-Host "Input file does not exist!"
Return
}
$Results = @()
#Checking log file
$Lines = Get-Content $InputFile
#Getting IP Addresses
Foreach ($Line in $Lines) {
$IP = ($Line | Select-String -Pattern "\d{1,3}(\.\d{1,3}){3}" -AllMatches).Matches.Value
ForEach ($I in $IP) {
IF ($I -notmatch "0.0.0.0|172.31.45.134|47.217.*") {
$Object1 = New-Object PSObject -Property @{
IPAddress = $I
}
$Results += $Object1
}
}
}
# Get list of IPs
$Final = $Results | Select-Object IPAddress -ExpandProperty IPAddress
# Group, sort, write to file
$Final | Group-Object -NoElement | Sort-Object Count -Descending | Out-File $OutputFile
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment