File actions with Microsoft Graph for SharePoint Online
This time I will cover the steps for using Microsoft Graph to upload, download and move files from and to SharePoint Online.
I chose to write about this subject because it describes the most common actions used with SharePoint Online. It also gives organizations a Microsoft supported alternative to coop with phasing out the NPA accounts (non-personal), now Microsoft is forcing Azure MFA for all users.
When we look at other options, we could use the PNP PowerShell module with a service principal, but then the module needs to be configured and there are no SLA’s or direct support from Microsoft for this open-source component. We could also use the SharePoint API, but this can only be used with a service principal based on certificate authentication.
All scripts can be found on my GitHub. Be careful and test it first before implementing it in production. |
Service principal with API permissions
Create an app registration (referred to as service principal) that we use for building the authentication token. Based on least privilege the Microsoft Graph Sites.Selected application permission will be the best option to assign to our new created service principal.
It’s necessary to add the service principal to every SharePoint site when using the Sites.Selected permissions. If you don’t want that, assign any of the other permissions: Sites.FullControl.All, Sites.Manage.All, Sites.ReadWrite.All, Sites.Read.All. Remember that it will give that permission for the service principal on all SharePoint sites!
We need to build an authentication token that we can use to do invoke-RestMethod actions. |
Give service principal permissions on SharePoint site
This step is only necessary when the Microsoft Graph API Sites.Selected permission is assigned to the service principal.
The service principal permissionsneed to be assigned on each SharePoint site when the Sites.Selected permissions are assigned. The following permissions can be assigned: read, write, fullcontrol and manage. An example for assigning permissions with the Microsoft Graph API.
New-UploadSPO
This function can be used to upload one or more files to a specific SharePoint folder. It will check if the source and destination exist. If no DestinationPath is specified, the file(s) will be uploaded to the root of the site.
New-DownloadSPO
This function will download all the files based on specified file extension to a named folder on the local machine. It’s possible to move the downloaded files from one SharePoint folder to another by using the MovePath variable.
The function will automatically fill the $global:collItems variable, that contains the FileName and CreatedBy properties for each file, so it can potentially be used elsewhere in your script.
[avs_posts_tag]