Passing Credentials in SharePoint Online Using PowerShell

Introduction 

 
This article will describe different ways of managing the credentials for SharePoint online using PowerShell.
 
We can pass the credentials in three different ways.
 
Using Secured String
 
In this type, we are hardcoding the username and password and then passing it for authentication.
 
Disadvantage
 
The password is visible to everyone who has access to the PowerShell script. 
 
Using File
 
By using this file, we can secure our credentials a little bit, as the password is stored in encrypted format. 
 
Disadvantage
 
The secret file is stored at the local drive on our computer and can be decrypted using some tools.
 
Using Window Credential Manager.
 
This type is the most secured and recommended way to pass the credentials.
 
Disadvantage
 
In this type, the user should have admin right, otherwise, it will prompt for credentials everytime we run the script.
 
Using Secured String
 
Hardcode the credentials in the following variables:
  1. $Username="Your userName"  
  2. $Password="Your Password"  
 The complete code will look like:
  1. Function Login-SharePointOnline()  
  2. {  
  3. Try {  
  4.         #Get Credentials to connect  
  5.   
  6.         $Username="Your userName"  
  7.         $Password="Your Password"  
  8.         $ListName="List Name"  
  9.         $siteURL="Site Url"  
  10.         $query = "<View>  
  11.                </View>"  
  12.         $securePassword = ConvertTo-SecureString $Password -AsPlainText -Force  
  13.         $Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username, $securePassword)  
  14.         $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)  
  15.         $Ctx.Credentials = $Cred  
  16.  
  17.         #check context available or not  
  18.         if (-not($Ctx)) {  
  19.             Write-Host "Error connecting to SharePoint Online, unable to establish context" -foregroundcolor black -backgroundcolor Red  
  20.             return  
  21.         }   
  22.         else   
  23.         {  
  24.             Write-Host "Connected to the Sharepoint Online successfully" -foregroundcolor green  
  25.         }  
  26.          #Get CAML Query object  
  27.         $camlquery = New-Object Microsoft.SharePoint.Client.CamlQuery;  
  28.         $camlquery.ViewXml= $query   
  29.          
  30.         $List = $Ctx.Web.Lists.GetByTitle($ListName)  
  31.         $Items = $List.GetItems($camlquery)  
  32.         $Ctx.Load($Items)  
  33.         $Ctx.ExecuteQuery()  
  34.          
  35.         #Get each value from list and print  
  36.         ForEach($Item in $Items)  
  37.         {   
  38.             Write-Host "Item in the List is:"$Item["Title"]  
  39.         }  
  40.         Write-Host $SourceList  
  41.           
  42.     }  
  43.     catch   
  44.     {  
  45.         Write-Host "Error connecting to SharePoint Online: $_.Exception.Message" -foregroundcolor black -backgroundcolor Red  
  46.         return  
  47.     }  
  48. }  
  49. #Calling function   
  50. Login-SharePointOnline  

Using File

 
Follow the below steps to create a secret file and write the username and password into that file. 
 
Step 1
 
I have created folder Arvind\safe under (D:\) drive. (You can create your own directory to save the secretfile).
 
Step 2 
 
Open powershell window run as administrator and run the following script which will prompt for credentials.
  1. $credentials = Get-Credential                                                                     
  2. $filename = 'D:\Arvind\safe\secretfile.txt'  
  3. $credentials | Export-Clixml -path $filename  
 Passing Credentials In SharePoint Online Using PowerShell
 
Provide your username and password and click the OK button to generate the secret file.
 
Ensure that the secret file is generated at our directory (D:\Arvind\safe\) and that it contains the username and password (encrypted format).
 
Passing Credentials In SharePoint Online Using PowerShell 
 
Step 3
 
To read and pass the credentials to sharepoint online, include the following lines in the script:
  1. $credPath = 'D:\Arvind\safe\secretfile.txt'  
  2. $fileCred = Import-Clixml -path $credpath  
  3. $Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($fileCred.UserName, $fileCred.Password)  
 The complete script for passing the credentials using file will look like the following:
  1. Function Login-SharePointOnline()  
  2. {  
  3. Try {  
  4.         #Get Credentials to connect  
  5.   
  6.         $ListName="ListName"  
  7.         $siteURL="Site URL"  
  8.         $query = "<View>  
  9.                </View>"  
  10.         $credPath = 'D:\Arvind\safe\secretfile.txt'  
  11.         $fileCred = Import-Clixml -path $credpath  
  12.         $Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($fileCred.UserName, $fileCred.Password)  
  13.         $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)  
  14.         $Ctx.Credentials = $Cred  
  15.  
  16.         #check context available or not  
  17.         if (-not($Ctx)) {  
  18.             Write-Host "Error connecting to SharePoint Online, unable to establish context" -foregroundcolor black -backgroundcolor Red  
  19.             return  
  20.         }   
  21.         else   
  22.         {  
  23.             Write-Host "Connected to the Sharepoint Online successfully" -foregroundcolor green  
  24.         }  
  25.          #Get CAML Query object  
  26.         $camlquery = New-Object Microsoft.SharePoint.Client.CamlQuery;  
  27.         $camlquery.ViewXml= $query   
  28.          
  29.         $List = $Ctx.Web.Lists.GetByTitle($ListName)  
  30.         $Items = $List.GetItems($camlquery)  
  31.         $Ctx.Load($Items)  
  32.         $Ctx.ExecuteQuery()  
  33.          
  34.         #Get each value from list and print  
  35.         ForEach($Item in $Items)  
  36.         {   
  37.             Write-Host "Item in the List is:"$Item["Title"]  
  38.         }   
  39.     }  
  40.     catch   
  41.     {  
  42.         Write-Host "Error connecting to SharePoint Online: $_.Exception.Message" -foregroundcolor black -backgroundcolor Red  
  43.         return  
  44.     }  
  45. }  
  46. #Calling function   
  47. Login-SharePointOnline  

Using Window Credential Manager

 
First, we require SharePoint Online PnP cmdlets to use the above method.
 
To install the SharePoint online cmdlets refer the following article or enter the following command in PowerShell. 
  1. Install-Module SharePointPnPPowerShellOnline  
Step 1
 
Open the window credential manager by typing credential manager in the search options.
 
Step 2
 
Click on Add a generic credential link under windows credentials.
 
Passing Credentials In SharePoint Online Using PowerShell
 
Step 3
 
Enter the following details and click on the ok button.
 
Note
Under Internet or network address, it is a logical name that is used in the script to read the credentials. 
 
Passing Credentials In SharePoint Online Using PowerShell
Step 4
 
To read the credentials from the window credentials manager pass the logical name(created in step 3) as a parameter in the script.
  1. Connect-PnPOnline -Url $siteURL -Credentials SharePointCredentials 
The complete code for passing the credentials using PNP cmdlets and window credentials manager is as follows:
  1. Function Login-SharePointOnline()  
  2. {  
  3. Try {  
  4.   
  5.         $ListName="ListName"  
  6.         $siteURL="site Url"  
  7.         Connect-PnPOnline -Url $siteURL -Credentials SharePointCredentials  
  8.         $ctx = Get-PnPContext  
  9.         #check context available or not  
  10.         if (-not($Ctx)) {  
  11.             Write-Host "Error connecting to SharePoint Online, unable to establish context" -foregroundcolor black -backgroundcolor Red  
  12.             return  
  13.         }   
  14.         else   
  15.         {  
  16.             Write-Host "Connected to the Sharepoint Online successfully" -foregroundcolor green  
  17.         }  
  18.          #Get CAML Query object  
  19.         $camlquery = New-Object Microsoft.SharePoint.Client.CamlQuery;  
  20.         $camlquery.ViewXml= $query   
  21.          
  22.         $List = $Ctx.Web.Lists.GetByTitle($ListName)  
  23.         $Items = $List.GetItems($camlquery)  
  24.         $Ctx.Load($Items)  
  25.         $Ctx.ExecuteQuery()  
  26.          
  27.         #Get each value from list and print  
  28.         ForEach($Item in $Items)  
  29.         {   
  30.             Write-Host "Item in the List is:"$Item["Title"]  
  31.         }  
  32.     }  
  33.     catch   
  34.     {  
  35.         Write-Host "Error connecting to SharePoint Online: $_.Exception.Message" -foregroundcolor black -backgroundcolor Red  
  36.         return  
  37.     }  
  38. }  
  39. #Calling function   
  40. Login-SharePointOnline  
 The complete script can be downloaded from attachment.