powershell_iconThe more I learn and get to know PowerShell, the more I love it.  I am able to perform what used to be time-consuming tasks (many hours or days) in seconds (after you write the script of course).  While writing a script recently to perform some tasks on numerous SharePoint sites (webs to be precise), I was constructing URLs for the sites and using as variables and I needed only part of the URL (the managed path).  After a little poking around, I found a nice easy way to do it.

Some Quick Background

In SharePoint (among other things), URLs can be of two different types, absolute and relative.  The absolute URL for an object is the full path direct to that object, where the relative URL is an abbreviated path that combines the base URL and the current location.  Let’s look a couple examples:

Absolute URL

  • http://portal/sites/hr/shared documents/newhire_policy.docx

Relative URL

  • /sites/hr/shared documents/newhire_policy.docx

The relative URL removes the base URL http://portal, which is the root web of the web application.  This becomes important especially if you use SSL on a web application, where you allow access via SSL and non-SSL, or if you use Alternate Access Mappings.  If you use absolute URLs, the other website will never get used.  This is why it is crucial to use relative paths to URLs in your navigation links like a good SharePoint administrator.  But I digress… on to PowerShell!

Without checking, I first solved this problem the complicated way.  I would enumerate the full URL, and then only grab the text 5 or however many characters I wanted to remove.  You can do this by using $webURL.Substring(3), where 3 is the number of characters you want to remove.  If you do this, be sure to do this on the URL as a string, NOT a web object as Substring is not a method on the web object, but is available on strings.  You could have also have used the TrimStart method as well I suppose.

This worked, but there had to be a better way!  In PowerShell, I think one of the most powerful commands to get to know is Get-Member.  Using this, I discovered a property called ServerRelativeURL on both a site object (site collection) or web object.  To see this, you pass (pipe) the site or web object to the get-member command like this:

   1: get-spweb http://contoso.intranet.com/it/sandbox | get-member

This returns all methods and properties of that object (our subsite in this case).  There are two properties that are related, Url and ServerRelativeURL.  So let’s look at this:

   1: $web = get-spweb http://contoso.intranet.com/it/sandbox 
   2: $web.ServerRelativeURL

The result is:


Voila!  Exactly what I needed.  We can then store this in a variable, and use it wherever we need it.  As you might expect, Url returns the absolute URL of the object. I strongly encourage you to investigate get-member, It opens up some many possibilities to view and/or various properties of almost anything.  Hope it helps!