Last active
June 8, 2023 20:40
-
-
Save heaths/eea37dc4bffb7be6de478e6f480a585f to your computer and use it in GitHub Desktop.
Simple PowerShell script to extract and test URLs in text files.
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 7.2 | |
[CmdletBinding(DefaultParameterSetName = 'Path')] | |
param ( | |
[Parameter(Mandatory, Position = 0, ParameterSetName = 'Path', ValueFromPipeline, ValueFromPipelineByPropertyName)] | |
[string[]] $Path, | |
[Parameter(Mandatory, ParameterSetName = 'LiteralPath', ValueFromPipelineByPropertyName)] | |
[string[]] $LiteralPath, | |
[Parameter()] | |
[ValidateCount(2, 3)] | |
[string[]] $Replace | |
) | |
begin { | |
$typeData = @{ | |
TypeName = 'ContentLinks.LinkResult' | |
DefaultDisplayProperty = 'URI' | |
DefaultDisplayPropertySet = 'IsValid', 'StatusCode', 'URI' | |
DefaultKeyPropertySet = 'URI' | |
} | |
Update-TypeData @typeData -Force | |
$uris = @() | |
} | |
process { | |
$replaceArgs = $Replace | |
[void] $PSBoundParameters.Remove('Replace') | |
$m = Select-String @PSBoundParameters -Pattern 'https?://[\w\.:\/%~_\-\+]+' -NoEmphasis | |
if (!$m) { | |
return | |
} | |
$m = $m | Select-Object @{l = 'URI'; e = { $_.Matches.Value } }, Path | |
$uris += if ($replaceArgs) { | |
$m | ForEach-Object { | |
[PSCustomObject]@{ | |
URI = $_.URI -replace $replaceArgs | |
Path = $_.Path | |
} | |
} | |
} | |
else { | |
$m | |
} | |
} | |
end { | |
$uris | Group-Object -Property 'URI' | ForEach-Object -Parallel { | |
$uri = $_.Name | |
$paths = $_.Group.Path | |
Write-Verbose "Checking $uri" -Verbose | |
try { | |
$resp = Invoke-WebRequest $uri -SkipHttpErrorCheck -UseDefaultCredentials | |
[PSCustomObject]@{ | |
PSTypeName = 'ContentLinks.LinkResult' | |
IsValid = $resp.StatusCode -ge 200 -and $resp.StatusCode -lt 300 | |
URI = $uri | |
Path = $paths | |
StatusCode = $resp.StatusCode | |
StatusDescription = $resp.StatusDescription | |
} | |
} | |
catch { | |
[PSCustomObject]@{ | |
PSTypeName = 'ContentLinks.LinkResult' | |
IsValid = $false | |
URI = $uri | |
Path = $paths | |
StatusCode = $null | |
StatusDescription = $_.Exception.Message | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment