PowerShell: How to Extract Domain from URL


You can use the following syntax to extract a domain from a URL in PowerShell:

([System.Uri]$my_url).Host -replace '^www\.'

This particular example extracts the domain from the URL specified in the string variable named $my_url.

Note that this syntax uses the System.Uri class to extract a wide variety of information about the URL string.

The property that we’re interested in is named Host and returns a pattern such as www.example_url.com.

We then use the -replace operator to replace the www. pattern at the beginning ( ^ ) of the string with nothing, which simply removes the www. from the domain.

The following example shows how to use this syntax in practice.

Example: How to Extract Domain from URL in PowerShell

Suppose that we have the following URL stored in a string named $my_url:

  • https://www.collectingwisdom.com/about

Suppose that we would like to extract only the domain from this URL to get the following:

  • collectingwisdom.com

We can use the System.Uri class to obtain a variety of information about the URL:

$my_url = "https://www.collectingwisdom.com/about"
[System.Uri]$my_url

The following screenshot shows how to use this syntax in practice:

Notice that the property named Host contains only the domain name.

We can use the following syntax to extract only the domain name and remove the www. pattern:

([System.Uri]$my_url).Host -replace '^www\.'

The following screenshot shows how to use this syntax in practice:

PowerShell extract domain from URL

Notice that this returns only the domain name collectingwisdom.com, which is exactly what we wanted.

Note: You can find the complete documentation for the System.Uri class here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Extract Substring After Specific Character
PowerShell: How to Replace Special Characters in String

Leave a Reply