I am trying to parse any given SharePoint URL and get back the site, web and list references using the code below. I would like to achieve this even if I provide the URL of an item. The code below works if i provide the URL of the list/library. If i provide the URL of an item in a list/library it throws an exception but also appears to work.
I do not understand why I am getting an exception when using an Item URL. What else do i need to do to make this work for any URL?
Code -
$listURL = "http://portal.contoso.com/sites/TEST/Shared%20Documents/Forms/AllItems.aspx"
$listURLWithItem= "http://portal.contoso.com/sites/TEST/Shared%20Documents/Test2.docx"
$site = New-Object Microsoft.SharePoint.SPSite($listURL)
$web = $site.OpenWeb()
$list = $web.GetListFromWebPartPageUrl($listURL)
"Output with list url-"
$site.url
$web.url
$list.Title
"Output when using item url-"
$site = New-Object Microsoft.SharePoint.SPSite($listURLWithItem)
$web = $site.OpenWeb()
$list = $web.GetListFromWebPartPageUrl($listURLWithItem)
$site.url
$web.url
$list.Title
The resulting output - with the second instance generating an exception
Output with list url-
http://portal.contoso.com/sites/TEST
http://portal.contoso.com/sites/TEST
Shared Documents
Output when using item url-
Exception calling "GetListFromWebPartPageUrl" with "1" argument(s): "Cannot complete this action.
Please try again."
At line:15 char:39
+ $list = $web.GetListFromWebPartPageUrl <<<< ($listURLWithItem)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
http://portal.contoso.com/sites/TEST
http://portal.contoso.com/sites/TEST
Shared Documents