Mastodon

[Powershell] Need URLs? There's a type-accelerator for that.

Aug 15, 2019

How many times have we all needed to store a URI string in our scripts? And of those times, how many times have we needed to parse them in some way? Whether it's interacting with a REST API, downloading a file, or scraping a site, this is a very common need in any programming language.

Here's a common example of how you might store a URI resource and parse it in Powershell. First, I'll use the [string] type-accelerator to cast it to a string.

PS> [string] $Uri = 'https://www.natelab.us/author/nate/'
PS> $Uri
https://www.natelab.us/author/nate/

You could then parse the domain portion several ways:

PS> ($uri -split '/')[2]
www.natelab.us

Or even worse:

PS> $Uri.Substring(8,14)
www.natelab.us

Gross. There are multiple problems with this approach - what if the site switches from using HTTP to HTTPS? Your sub-string match would break. The -split method might work, but it's text manipulation, and since this is Powershell, why not use an object-oriented approach?

There must be a better way. (Spoiler: there is)

The [URI] type-accelerator is derived from the corresponding .NET class of the same name. You can read more on this resource at Microsoft's documentation here.

When we use this new class, our results are different as we're returning a Uri object, instead of a string object:

PS> [uri] $Uri = 'https://www.natelab.us/author/nate/'

AbsolutePath   : /author/nate/
AbsoluteUri    : https://www.natelab.us/author/nate/
LocalPath      : /author/nate/
Authority      : www.natelab.us
HostNameType   : Dns
IsDefaultPort  : True
IsFile         : False
IsLoopback     : False
PathAndQuery   : /author/nate/
Segments       : {/, author/, nate/}
IsUnc          : False
Host           : www.natelab.us
Port           : 443
Query          :
Fragment       :
Scheme         : https
OriginalString : https://www.natelab.us/author/nate/
DnsSafeHost    : www.natelab.us
IdnHost        : www.natelab.us
IsAbsoluteUri  : True
UserEscaped    : False
UserInfo       :

Now THAT looks better.

At this point, you can simply retrieve any property you want. Our example of the domain from earlier:

PS> $uri.Host
www.natelab.us

This is a short post, but I hope it brings to light an easier way to interact with Uri resources in Powershell!

Tags