Parse all Files in a Directory and Extract IP Addresses to hash file

# Define the root directory and output hash file
$rootDir = "C:\Temp\DirectoryWithFilesWithIPs"
$hashFile = "C:\Temp\ip_hashes.txt"

# Regular expression pattern for IPv4 addresses
$ipPattern = '\b(?:\d{1,3}\.){3}\d{1,3}\b'

# Clear or create the hash file
"" | Out-File -FilePath $hashFile -Encoding UTF8

# Initialize a counter for redaction IDs
$global:redactionCounter = 1

# Process each file
Get-ChildItem -Path $rootDir -Recurse -File | ForEach-Object {
    $filePath = $_.FullName
    $content = Get-Content -Path $filePath -Raw
    $modified = $false

    # Replace each IP with a unique redaction tag
    $newContent = [regex]::Replace($content, $ipPattern, {
        param($match)
        $tag = "[REDACTED_$($global:redactionCounter)]"
        "$filePath : $tag => $($match.Value)" | Out-File -FilePath $hashFile -Append -Encoding UTF8
        $global:redactionCounter++
        return $tag
    })

    # Save the modified content back to the file
    if ($newContent -ne $content) {
        Set-Content -Path $filePath -Value $newContent -Encoding UTF8
    }
}

Leave a Reply

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