Search code examples
powershellmicrosoft-graph-apibase64httprequest

Creating Encoded Url for Microsoft Graph using PowerShell


I have uploaded a file to OneDrive and added invited a user to access the file. The sharing Url works well for that user. I would like to take that same Url and grant additional users access to the file.

It looks like I should be able to use the following request to add additional users access with that link. POST /shares/{encoded-sharing-url}/permission/grant https://learn.microsoft.com/en-us/graph/api/permission-grant?view=graph-rest-1.0&tabs=http

I am having an issue getting an encoded Url that the graph will accept. All of my requests have received the following responses.

{
  "error": {
    "code": "invalidRequest",
    "message": "The provided shares id is not valid.",
    "innerError": {
      "code": "badArgument",
      "date": "2023-02-21T04:50:01",
      "request-id": "85e712ce-efd7-4d42-8cde-1b7133adaa9e",
      "client-request-id": "85e712ce-efd7-4d42-8cde-1b7133adaa9e"
    }
  }
}

I have been using the following example for encoding in base64 https://shellgeek.com/powershell-base64-encoding/#PowerShell_Base64_Encode_String:~:text=files%20in%20PowerShell!-,PowerShell%20Base64%20Encode%20String,-Let%E2%80%99s%20understand%20with

$StringMsg = "PowerShell Base64 Encode Example"
# Gets the bytes of String
$StringBytes = [System.Text.Encoding]::Unicode.GetBytes($StringMsg)
# Encode string content to Base64 string
$EncodedString =[Convert]::ToBase64String($StringBytes)
Write-Host "Encode String: " $EncodedString

Being sure to replace / with _ and + with - as well as making sure there's no = at the end.

Is there a trick to get this encoded correctly?


Solution

  • I'm using similar script but with UTF8 encoding instead of Unicode

    $stringMsg = "PowerShell Base64 Encode Example"
    $base64Value = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($stringMsg))
    $encodedUrl = "u!" + $base64Value.TrimEnd('=').Replace('/','_').Replace('+','-')
    Write-Output($encodedUrl)
    

    Result

    u!UG93ZXJTaGVsbCBCYXNlNjQgRW5jb2RlIEV4YW1wbGU