Home > Reshmee Auckloo, Work > Instantiate SharePoint Client Context using current user credentials in PowerShell

Instantiate SharePoint Client Context using current user credentials in PowerShell

In C# managed code, SharePoint Client Context can be created using System.Net.CredentialCache to pass logged in user credentials.

ICredentials credentials = CredentialCache.DefaultCredentials;
clientContext.Credentials = credentials;

I could not find anywhere how to achieve it in PowerShell.

If using PnP PowerShell module, the switch parameter CurrentCredentials can be used with the cmdlet Connect-Online.

Connect-SPOnline -Url “http://dev-sp-001a:1214/Teams/Legal” -CurrentCredentials 
$ctx= Get-SPOContext

In most of my CSOM code without use of PnP I used to get current user name using [Environment]::UserName

[Environment]::UserName

I used to prompt the current user to enter password

$AdminPassword = Read-Host "Enter password: " -AsSecureString

Lately I discovered I could use  system.net.credentialcache in PowerShell  to pass current user credentials when instantiating the ClientContext object.

 $ctx=New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) 
 $Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
 $ctx.Credentials = $Credentials;
 $web = $ctx.Web
 $ctx.Load($web);
 $ctx.ExecuteQuery();

This means you can start Windows PowerShell as the user having appropriate permissions to the SharePoint Environment and run CSOM code without prompting credentials.

from reshmeeauckloo http://bit.ly/2e34K7M

Reshmee Auckloo
Reshmee Auckloo – Reshmee is a certified Microsoft professional and has been involved in delivering solutions across a wide variety of industry sectors in a range of assignments from SSRS to Microsoft SharePoint, Project Server development, CRM Dynamics and .Net including business requirements gathering and software quality assurance.

This article has been cross posted from reshmeeauckloo.wordpress.com (original article)

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: