Execute C# code from PowerShell Script – SharePoint Online

Are you looking for an example code to exeucte C# code from PS?

Hope you can get started with the below sample. As per your requirement change the DLL path, Site URL, UserName and Password parameters in the below example.

cls

# C# Source Code
$SourceCode = @”
using System;
using System.Management.Automation;
using System.Security;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Utilities;

namespace SPOperations
{
public class SPHelper
{
public static string getWebTitle(string siteUrl, string userName, string sitePassword)
{
using (ClientContext clientContext = new ClientContext(siteUrl))
{
SecureString passWord = new SecureString();
foreach (char c in sitePassword.ToCharArray()) passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(userName, passWord);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
return web.Title;
}
}
}
}
“@

try
{
$scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
Set-Location $scriptBase

$TenantConfig = $scriptBase + “\” + “Configs\settings.xml”
$TenantConfigXML = [xml](Get-Content($TenantConfig));

$url = $TenantConfigXML.ConnectionString.Key.URL
$username = $TenantConfigXML.ConnectionString.Key.UserName
$password = $TenantConfigXML.ConnectionString.Key.Password

$assemblies = @(
“$scriptBase\DLL\Microsoft.SharePoint.Client.dll”,
“$scriptBase\DLL\Microsoft.SharePoint.Client.Runtime.dll”
“System.Core”
)
}
catch
{
Write-host “Error while loading the input parameters ” $_.Exception.Message -ForegroundColor Red
exit 1
}

try
{
#Add the Assembly
Add-Type -ReferencedAssemblies $assemblies -TypeDefinition $SourceCode -Language CSharp
}
catch
{
Write-host “Error while loading the Referenced Assemblies and Type Definition ” $_.Exception.Message -ForegroundColor Red
exit 1
}

try
{
$siteTitle = [SPOperations.SPHelper]::getWebTitle($url, $username, $password)
Write-Host $siteTitle
}
catch
{
Write-host “Error : ” $_.Exception.Message -ForegroundColor Red
exit 1
}

Advertisements

About Joseph Velliah
As a SharePoint Developer my professional interests tend to be technical and SharePoint focused. I run a blog at "SP RIDER" where you can expect to read HOW TOs and scenarios that I run into during my day to day job. I hope my posts will give back a little to the community that is helped me.

Comments are closed.

%d bloggers like this: