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 = ''
PS> $Uri

You could then parse the domain portion several ways:

PS> ($uri -split '/')[2]

Or even worse:

PS> $Uri.Substring(8,14)

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 = ''

AbsolutePath   : /author/nate/
AbsoluteUri    :
LocalPath      : /author/nate/
Authority      :
HostNameType   : Dns
IsDefaultPort  : True
IsFile         : False
IsLoopback     : False
PathAndQuery   : /author/nate/
Segments       : {/, author/, nate/}
IsUnc          : False
Host           :
Port           : 443
Query          :
Fragment       :
Scheme         : https
OriginalString :
DnsSafeHost    :
IdnHost        :
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

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