Created
November 28, 2024 23:46
-
-
Save json-m/63f88260fe147b02b2c30fd0c72f83b1 to your computer and use it in GitHub Desktop.
tails a log file and prints urls to console
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Requires -Version 2.0 | |
param( | |
[Parameter(Mandatory=$true)] | |
[string]$logFile | |
) | |
# Convert relative path to absolute path | |
$logFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($logFile) | |
# URL regex pattern that matches http, https, ftp, and other common protocols | |
$urlPattern = '(https?|ftp|file|sftp|ws|wss):\/\/[-A-Za-z0-9+&@#\/%?=~_|!:,.;]*[-A-Za-z0-9+&@#\/%=~_|]' | |
# Verify the file exists | |
if (-not (Test-Path $logFile)) { | |
Write-Error "File not found: $logFile" | |
exit 1 | |
} | |
# Create a StreamReader for continuous reading | |
try { | |
$reader = New-Object System.IO.FileStream($logFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite) | |
$streamReader = New-Object System.IO.StreamReader($reader) | |
# Seek to the end of the file | |
$reader.Seek(0, [System.IO.SeekOrigin]::End) | |
Write-Host "Monitoring $logFile for URLs..." | |
while ($true) { | |
$line = $streamReader.ReadLine() | |
if ($line -ne $null) { | |
# Search for URLs in the line | |
if ($line -match $urlPattern) { | |
# Extract all matches and print them | |
$matches = [regex]::Matches($line, $urlPattern) | |
foreach ($match in $matches) { | |
Write-Host $match.Value | |
} | |
} | |
} else { | |
# No new lines, wait briefly before checking again | |
Start-Sleep -Milliseconds 100 | |
} | |
} | |
} | |
catch { | |
Write-Error $_.Exception.Message | |
exit 1 | |
} | |
finally { | |
if ($streamReader) { $streamReader.Dispose() } | |
if ($reader) { $reader.Dispose() } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment