Run SharePoint Online cmdlets in an Azure Function App

Functions_LogoInterested in deploying your SharePoint PowerShell scripts to Azure? Stick ’em in an Azure Function App! All the perks of a scheduled job but with an optional HTTP endpoint for invocation.

To get the SPO cmdlets available there are a few things you need to do.

First, download the SharePoint Online Management Shell to your own machine.

Once installed, navigate to the location of the installed assemblies. A quick way of finding out the location is to pull up the SharePoint Management Shell and type:

[appdomain]::currentdomain.getassemblies()

Locate the SharePoint Online assemblies and you’ll find their location:

2017-03-20 20_43_38-SharePoint Online Management Shell

Navigate up a level and zip the whole Microsoft.Online.SharePoint.PowerShell folder:

2017-03-20 20_49_17-SharePoint Online Management Shell

Next, open up your Azure Function App and from the Filepane, upload your zip file:

2017-03-20 20_51_53-RaysTestContainer - Microsoft Azure

 

Once uploaded, open the debug console page of your function:

https://<function name>.scm.azurewebsites.net/DebugConsole

CD to your app directory and unzip the archive:

unzip Microsoft.Online.SharePoint.PowerShell.zip

2017-03-20 20_58_24-Diagnostic Console

It will unpackage all the necessary dlls to the directory.

Move back to the </>Develop section of your function. At the start of your code pull in the assemblies using:

Import-Module "D:\home\site\wwwroot\SiteCollectionStorageUsage\Microsoft.Online.SharePoint.PowerShell" -DisableNameChecking

Replace SiteCollectionStorageUsage with the name of your function.

With the assemblies referenced you will be able to run SPO cmdlets:

2017-03-20 21_04_37-RaysTestContainer - Microsoft Azure

 

And there you have it! The above example spits out some usage stats of the tenant’s site collections, but you have the whole suite of cmdlets at your disposal, so there’s a lot more you do with them. Enjoy!