Checking for valid Url using TryCreate


I’ve been working with Sharepoint online and needed to validate that a user is passing me a valid url.  So after doing some searching i found that [system.uri] had some methods that were useful.  In particular there is a method called TryCreate. This will take a url that you send to the method and let you know if it is a valid uri or not.

So first lets start with a url that we know is valid: Bing.com

TryCreate Expects Three values to be passed to it.

The first is a String or uri as you can see here.

The second is a System.urikind.   As you can see this is an enumeration that has three possible values, Absolute, Relative, and RelativeOrAbsolute

The third is a [ref]erence.  What this means is I must declare a variable for the return result to be put into after the method evaluates what was passed to it.

trycreate

Here is what that looks like in practice. Note I must use [ref] for my return result as it is used as a reference to get the results into.

$url = 'http:\\bing.com'
$kind = 'RelativeOrAbsolute'
$return = $null

[system.uri]::TryCreate($url,$kind,[ref]$return)

Now if I run this I’ll get the following output:

 $kind = 'RelativeOrAbsolute'
$return = $null

[system.uri]::TryCreate($url,$kind,[ref]$return)
True

Now if I look at my return variable we’ll notice that it has a full object with values.

 PS Z:\> $return


AbsolutePath : /
AbsoluteUri : http://bing.com/
LocalPath : /
Authority : bing.com
HostNameType : Dns
IsDefaultPort : True
IsFile : False
IsLoopback : False
PathAndQuery : /
Segments : {/}
IsUnc : False
Host : bing.com
Port : 80
Query : 
Fragment : 
Scheme : http
OriginalString : http:\\bing.com
DnsSafeHost : bing.com
IdnHost : bing.com
IsAbsoluteUri : True
UserEscaped : False
UserInfo :

Now I can use my return value and test to see if the value returned is of type HTTP or HTTPS.

if($return -like 'http*')
{
    write-output 'This is a http or https address'
}

This is a http or https address

You could write several other test’s to figure out what Scheme of uri the user passed. I’ll leave that up to your scripting.  Here is a link to the rest of the uri Schemes

 

 

I hope this helped someone

Until then keep scripting

Thom

Advertisement

2 thoughts on “Checking for valid Url using TryCreate

  1. crshnbrn66

    Nice that would cover both the http and https.. I was thinking of making a switch with this so you’d know what kind of Scheme you’d be using. With what you posted maybe a REGEX would be better.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s