将Powershell Connect-PnPOnline转换为C#

时间:2018-09-07 07:07:40

标签: c# powershell sharepoint sharepoint-online

寻找如何将共享点PnP的许多Powershell转换为C#

示例:from django.contrib.auth.views import LogoutView url(r'^logout/$', LogoutView.as_view(), {'next_page': settings.LOGOUT_REDIRECT_URL}, name='logout'),

一些Powershell

Connect-PnPOnline

要在C#应用程序中使用它吗?

这里有一些更具体的Powershell可以“运行”,但是github示例库没有那么大的帮助。

$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

1 个答案:

答案 0 :(得分:1)

PnP PowerShell会将很多内容隐藏起来,以简化您的工作。

要将代码修改为C#,需要按如下所述编写:

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;
}

要执行此代码,您需要在项目中使用Microsoft.SharePointOnline.CSOM nuget程序包。