Connecting to SharePoint Online using the PnP PowerShell Library and NOT Having to Log In Every. Single. Time…

imageBefore 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 –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 = ""
$Password = "ThisIsNotMyRealPassword!"
$SiteCollection = ""
#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
} catch {
    Write-Host "Error connecting to SharePoint Online: $_.Exception.Message" -foregroundcolor black -backgroundcolor Red
#endregion ConnectPnPOnline

SharePoint Patterns and Practices Cmdlet Reference Guide Now Available

Finally here! Microsoft has released a reference guide for the over 200 Patterns and Practices Cmdlets!


Check it out here:

%d bloggers like this: