Tuesday, May 8, 2018

How to get the list item from a file URL using PnP PowerShell

Photo by Karly Santiago at Unsplash

This is one of the snippets I always forget, but which is very handy in cases where you have the absolute URL to an item in SharePoint. The magic is really line 6 which uses the static method WebUrlFromFolderUrlDirect to get the web URL of the file, so that you can connect properly.

[Updated 2021-01-19 to support "People with existing access" sharing URL's]

$uri = [Uri]'https://contoso.sharepoint.com/sites/foo/bar/Shared%20Documents/mikael-is-cool.docx'.replace(":w:/r/","")
$uri = [Uri]$uri.OriginalString.Replace($uri.Query,"")
# Connect to the root site, or any other site
Connect-PnPOnline -Url ($uri.Scheme+'://'+$uri.Host)
$ctx = Get-PnPContext
# Get the web url for the file
$webUrl = [Microsoft.SharePoint.Client.Web]::WebUrlFromFolderUrlDirect($ctx, $uri)
Connect-PnPOnline -Url $webUrl
$fileItem =  Get-PnPFile -Url ([System.Web.HttpUtility]::UrlDecode($uri.AbsolutePath)) -AsListItem