Blog about anything related to my learnings
  • About
  • posts
bluesky
Blog about anything related to my learnings
POSTS

If you try get-pnpfile using full path, the url needs to be encoded. There are loads of issues with special charaters like [ ] becomes %5B and %5D in

    $encodedfileUrl = [System.Web.HttpUtility]::UrlPathEncode($fileUrl)

    $item = Get-PnPFile -Url $encodedfileUrl -AsListItem -ErrorAction Stop
    
    Log-Message "Retrieved file: $fileUrl" "Success"

Those two methods don’t handle [ ] [System.Web.HttpUtility]::UrlPathEncode(…): obsolete and doesn’t encode [/]. [System.Uri]::EscapeUriString(…): does not encode [ and ] and may leave other characters unencoded.

Instead could use the following

$uri       = [Uri]$fileUrl
$segments  = $uri.AbsolutePath -split '/'
$segments  = $segments | ForEach-Object {
    if ($_ -eq '') { '' } else { [System.Uri]::EscapeDataString($_) }
}

$encodedPath = ($segments -join '/')
$encodedFileUrl = "$($uri.Scheme)://$($uri.Host)$encodedPath"

However above method does not work well with other special characters like é , etc.. hence giving up on Url encode to use serverrelative Url

 $serverRelativeUrl = $fileURL.Replace($TenantUrl, "")
        
 # Ensure it starts with a slash
 if (-not $serverRelativeUrl.StartsWith("/")) {
     $serverRelativeUrl = "/" + $serverRelativeUrl
 }
        $item = Get-PnPFile -Url $serverRelativeUrl -AsListItem -ErrorAction Stop

With serverRelativeUrl, it does not to be encoded to be passed to the cmdlet, it’s handled behind the scenes by the code

    © Blog about anything related to my learnings 2026
    bluesky