4

Is it possible to get a Sitecore item via Powershell script having only the public URL?

Something like an overload of the Get-Item function that receives the URL would be ideal

Thanks in advance

3

You can get item by URL using below function. You may have to tweak it for resolving wildcard items.

function GetItemByUrl($url){
    $url = [System.Uri]::new($url);

    $siteContext = [Sitecore.Sites.SiteContextFactory]::GetSiteContext($url.Host, $url.PathAndQuery);

    $homePath = $siteContext.StartPath;
    if (!$homePath.EndsWith("/")){            
        $homePath += "/";
    }

    $itemPath = [Sitecore.MainUtil]::DecodeName($url.AbsolutePath);

    if ($itemPath.StartsWith($siteContext.VirtualFolder)){
        $itemPath = $itemPath.Remove(0, $siteContext.VirtualFolder.Length);
    }

    $fullPath = $homePath + $itemPath;
    return $siteContext.Database.GetItem($fullPath);
}

$item = GetItemByUrl("http://localhost.sc/my-page")

Write-Host $item.ID
2
  • Thanks, this looks good but what if the item is inside a bucket? Apr 22 '20 at 20:30
  • For that, you can check how Sitecore resolves URLs for bucket items, and then you can tweak the method accordingly. Apr 23 '20 at 8:36

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.