Before you can do anything with the SharePoint Patterns & Practices PowerShell library, you need to first connect to SharePoint Online. Sounds pretty basic, right? You need to establish who you are, and maintain your access during your session with the site you are working with.
Now, the Documentation does show you how to do this:

Connect-PnPOnline –Url https://geoff365.sharepoint.com –Credentials (Get-Credential)
When you do this… you are prompted for credentials… Every. Single. Time.

This is good for production, however, if you are developing a script, you may run this tens or hundreds of times… and, it gets old pretty fast. So, here is what I do. In my script, I set variables for the username and password (alternatively, you could pass these as parameters, and pass them along using a batch file).

Then, I convert the password into a secure string, and create a PSCredential object with the username and secure password.

I can then connect to SharePoint Online using the Connect-PnPOnline command (as shown above), wrapped in a try/catch block, and not be prompted for credentials!

Here’s the full script:
#region Imports
Import-Module SharePointPnPPowerShellOnline -WarningAction SilentlyContinue
#endregion Imports
#region Variables
$Username = "admin@geoff365.onmicrosoft.com"
$Password = "ThisIsNotMyRealPassword!"
$SiteCollection = "https://geoff365.sharepoint.com/sites/powershellplayground"
#endregion Variables
#region Credentials
[SecureString]$SecurePass = ConvertTo-SecureString $Password -AsPlainText -Force
[System.Management.Automation.PSCredential]$PSCredentials = New-Object System.Management.Automation.PSCredential($Username, $SecurePass)
#endregion Credentials
#region ConnectPnPOnline
try {
Connect-PnPOnline -Url $SiteCollection -Credentials $PSCredentials
if (-not (Get-PnPContext)) {
Write-Host "Error connecting to SharePoint Online, unable to establish context" -foregroundcolor black -backgroundcolor Red
return
}
} catch {
Write-Host "Error connecting to SharePoint Online: $_.Exception.Message" -foregroundcolor black -backgroundcolor Red
return
}
#endregion ConnectPnPOnline
Like this:
Like Loading...