#PSTip Test if a URL is absolute or not

The System.Uri class in .NET provides a way to validate if a URL is an absolute URL or not. This can be quite handy when your script deals with downloading content from web pages and there is a need to validate the specified URL.

The IsWellFormedUriString method provides this capability.

[system.uri]::IsWellFormedUriString($url,[System.UriKind]::Absolute)

The UriKind enumeration has three values–Absolute, Relative, and RelativeOrAbsolute. The IsWellFormedUriString() method returns a Boolean value based on the match.

I wrapped this in a small function called Test-Url:

Function Test-Url {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [String] $Url
    )

    Process {
        if ([system.uri]::IsWellFormedUriString($Url,[System.UriKind]::Absolute)) {
            $true
        } else {
            $false
        }
    }
}

And, here is a practical example where I am using this function.

$doc = Invoke-WebRequest -Uri 'https://www.python.org/downloads'
foreach ($href in ($doc.links.href -ne '')) {
    if (Test-Url -Url $href) {
        $href
    }
}
Share on: