6

Let's have, for example, this url: http://corp.com/sites/project1/documents/forms/allitems.aspx.

Is there an efficient way to analyse this full url to extract site and web url?

  • The web application url is http://corp.com (this one is easy to find, as it's the scheme + host)
  • The site url is http://corp.com/sites/project1
  • The web url is http://corp.com/sites/project1

When a SPContext is available, this is easy, but what about an external application? Typically, what about from a PowerShell script?

$fullUrl = "http://corp.com/sites/project1/documents/forms/allitems.aspx"
$siteUrl = ___($fullUrl)
$site = Get-SPSite $siteUrl

I know I could play with Get-SPSite -Limit All and compare url, but it may be tricky when nesting site collection, or have a large number of site collection.

Actually, I'm hoping Microsoft have an utility class that will do the job (but I didn't find it yet).

Any advise?

1 Answer 1

8

The normal constructor for a SPSite accepts any url and opens the Site Collection which is a best match. If you from that SPSite call OpenWeb() with no parameters you get the SPWeb corresponding to the Site which best match the url specified when created the SPSite. Unfortunately the PowerShell cmdlets don't allow you to do that, but then you just revert to using .Net directly like this:

$fullUrl = 'http://corp.com/sites/project1/documents/forms/allitems.aspx'
$site = New-Object -Type Microsoft.SharePoint.SPSite -ArgumentList $fullUrl
$web = $site.OpenWeb()
$site.Url
$web.Url
$web.Dispose()
$site.Dispose()
1
  • Thanks, this would do the trick. I imagine there are some limitation, regarding permissions, but I can live with that (or use RunWithElevatedPrivileges)
    – Steve B
    Commented Sep 24, 2013 at 10:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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