This is a pretty simple blog. Take one of the examples I've been using often:
This PowerShell uses PnP-PowerShell to:
- Connect to SharePoint Online
- Pulls a list from Document Library
- Format as HTML Table
- Send to an email with SPO SendMail utility endpoint
One of the most common, repeated step I do in almost every Function is to get credential and authenticate. So I decided to put it into a shared function.
Refactor this into a separate function
Use the file navigator on the right hand pane - add a new file, call it "shared.psm1" this is a PowerShell Module file.
Create a function get-cred() and put the 4 lines of getting $username and encode PSCredential into this function, then return $creds
Finally, reference the module via:
Import-Module "D:\home\site\wwwroot\get-list-and-email\shared.psm1" # call get-cred inline here Connect-PnPOnline -url $siteUrl -Credentials (get-cred)
The path is the name of the function, that points to the current directory.
From now on, in every other function, you can just import that module to share the function.
If you use a separate shared directory under the wwwroot\shared level - that's a good place to put these shared modules too. But note that you can't access that area via the Files right-hand pane. You'll need to go there via the Kudu interface.
I consider putting get-cred away as a preparation step for one day in the future where I would replace that function with a call to Azure KeyVault to obtain the PSCredential object. When that refactoring happens, I will only need to update one place.