#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
    }
}

About the author: Ravikanth C

Ravikanth is the founder and editor of the PowerShell Magazine. He is also a PowerShell MVP who works at Dell Inc. He blogs at http://www.ravichaganti.com/blog and you can follow him on Twitter @ravikanth.

Related Posts

%d bloggers like this: