Forum Discussion
Add link to SharePoint Document Library to OneDrive programmatically with PowerShell or PA
Hi there, I know this is an old thread but I was looking for the exact same solution and found a post somewhere sharing a solution. This solution didn't work though. It was purely theoretical and based on what that person found by using the developer dashboard and inspecting the calls that were made when someone actually uses that functionality from SharePoint. An HTTP POST call is made to https://tenantname-my.sharepoint.com/_api/v2.1/drives/me/items/root/children with a specific payload:
They proposed to replace the "me" in the request with the UPN of the user you want to target. The thing is, that API does not accept UPN's. It's only for "me".
BUT... there IS a different endpoint you can use that does target other users and that's this one:
https://graph.microsoft.com/v1.0/users/$upn/drive/root/children
And if you send that exact payload to this endpoint... the shortcut is created.
So, here's how i did it in PowerShell.
$upn = "email address removed for privacy reasons"
$assertionToken = GetClientCertificateAssertionToken -Certificate $certificate -TenantId $tenantId -AppId $clientId
$body = @{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
client_Id = $clientId
client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
client_assertion = $assertionToken
}
$tokenresponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -Method POST -Body $Body -ContentType "application/x-www-form-urlencoded"
$shortcutUrl = "https://graph.microsoft.com/v1.0/users/$upn/drive/root/children"
$shortcutBody = @{
"name" = "Documents"
"remoteItem" = @{
"sharepointIds" = @{
"listId" = "dece8bcb-ee96-445a-97ac-e9929f18dcc8"
"listItemUniqueId" = "root"
"siteId" = $siteId
"siteUrl" = "https://$tenantname.sharepoint.com/sites/TestTeam"
"webId" = "f8a11726-4760-4621-9634-88b58dfc607b"
}
}
"@microsoft.graph.conflictBehavior" = "rename"
} | ConvertTo-Json -Depth 3
$response = Invoke-RestMethod -Uri $shortcutUrl -Headers @{Authorization = "Bearer $($tokenresponse.access_token)"} -ContentType 'application/json' -Body $shortcutBody -Method POST
You obviously need an app registration with the correct Microsoft Graph API permissions (Sites.ReadWrite.All, Files.ReadWrite.All, and User.ReadWrite.All).
Tested. Works!
Perhaps this answer can serve as a reference for other people looking for the same thing.
Hi,
Does this still work for you? I'm testing right now, and that endpoint does not support POSTs. I searched around and only see PUTs, which require file content.