Warm tip: This article is reproduced from serverfault.com, please click

Convert Powershell Connect-PnPOnline to C#

发布于 2018-09-07 07:07:39

Looking for how I can convert a lot of powershell for the sharepoint PnP to C#

Example: Connect-PnPOnline

Some Powershell

$PasswordAsSecure = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential ($UserName , $PasswordAsSecure)
Connect-PnPOnline -Url $SiteUrl -Credentials $Credentials
$RootSiteContext = Get-PnPContext

# Determine the SharePoint version
$ServerVersion = (Get-PnPContext).ServerLibraryVersion.Major

For this to be in C# application?

Here is some more specific powershell that "works" but the github example libraries just are not that helpful.

                    Connect-PnPOnline -Url $hubUrl -Credentials $O365Credentials
                    $sc = Get-PnPSite
                    $w = Get-PnPWeb
                    $baseRelUrl=$w.ServerRelativeUrl
                    if (-not $baseRelUrl ) {
                          throw "hub site isn't created"
                    }
Questioner
Tom Stickel
Viewed
0
Gautam Sheth 2018-09-07 17:10:32

PnP PowerShell wraps a lot of stuff under the hood to make it easy for you.

To modify your code to C#, it needs to be written as mentioned below:

var siteUrl = "https://your-sitecollection-url";
var userName = "userName";
var password = "password";

using (ClientContext clientContext = new ClientContext(siteUrl))
{
    SecureString securePassword = new SecureString();
    foreach (char c in password.ToCharArray())
    {
        securePassword.AppendChar(c);
    }

    clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
    clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);

    clientContext.ExecuteQuery();

    var ServerVersion = clientContext.ServerLibraryVersion.Major;

    var site = clientContext.Site;
    var web = clientContext.Site.RootWeb;

    clientContext.Load(web, w => w.ServerRelativeUrl);
    clientContext.ExecuteQuery();

    var serverRelativeUrl = clientContext.Site.RootWeb.ServerRelativeUrl;
}

To execute this code, you will need Microsoft.SharePointOnline.CSOM nuget package in your project.