I want to extract root URL from full URL. how to extract that based on number of "/" in that.

for example:


from this URL i want to extract below root site(string before 5th "/").


Please assist how to achieve this in Powershell and in excel.



Either cast to an [uri] type and (re-)assemble the parts

> [uri]"https://teams.SharePoint.com/sites/site/communities/subsite"

AbsolutePath   : /sites/site/communities/subsite
AbsoluteUri    : https://teams.sharepoint.com/sites/site/communities/subsite
LocalPath      : /sites/site/communities/subsite
Authority      : teams.sharepoint.com
HostNameType   : Dns
IsDefaultPort  : True
IsFile         : False
IsLoopback     : False
PathAndQuery   : /sites/site/communities/subsite
Segments       : {/, sites/, site/, communities/...}
IsUnc          : False
Host           : teams.sharepoint.com
Port           : 443
Query          :
Fragment       :
Scheme         : https
OriginalString : https://teams.SharePoint.com/sites/site/communities/subsite
DnsSafeHost    : teams.sharepoint.com
IdnHost        : teams.sharepoint.com
IsAbsoluteUri  : True
UserEscaped    : False
UserInfo       :

Or use the -split and -join operators

## Q:\Test\2019\07\29\SP_267043.ps1
$Site = "https://teams.SharePoint.com/sites/site/communities/subsite"

$URI  = [uri]$Site
"{0}://{1}{2}" -f $Uri.Scheme,$Uri.Host,(-join $Uri.Segments[0..2])
($Site -split '/')[0..4] -join '/'

Sample output:

> Q:\Test\2019\07\29\SP_267043.ps1

Note the trailing / when joining segments.

  • I like this way of getting details from [uri]. Didn't know it before, thanks! Useful! – OneOfThePetes Jul 30 '19 at 11:57

There are a few ways to do this in PowerShell (on the SharePoint box).

All of the below examples will result with https://teams.SharePoint.com/sites/site

The best way is to call the Root Site Collection's Web:

$web = Get-SPWeb "https://teams.SharePoint.com/sites/site/communities/subsite"

You can try calling the Parent Web for each web (not as useful):

$web = Get-SPWeb "https://teams.SharePoint.com/sites/site/communities/subsite"

or even try calling the Parent's Root Site Collection Web (same result as the first example - all webs will have the same common root site collection web):

$web = Get-SPWeb "https://teams.SharePoint.com/sites/site/communities/subsite"

First example is the easiest. The other examples are just to show you the "ParentWeb" property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.