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.
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
You can try this for the match as well.
if ($return -match ‘\bhtt(ps|p):\/\/\b’)
Just playing about with Regular Expressions and your post inspired me to try something 🙂
Sean
The EnergizedTech
LikeLiked by 1 person
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.
LikeLike