Montag, 28. März 2011

How to: c# code in powershell script

I was looking for a way to add C# code to a powershell script, because sometimes you are not able to run everything with powershell.
It works like this:

first reference to the assemblies your code uses:
$referencingassemblies = (
"Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" ,
"Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c",
"System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
)


Then insert the source and store it in a variable. Be aware to have all the assemblies you are using referenced in your variable above:
$mysource = @"
using Microsoft.SharePoint.Publishing.Administration;
using Microsoft.SharePoint;
using System;
using System.Data;
using System.Xml;
using Microsoft.SharePoint.Publishing;

namespace MyNamespace
{
public static class MyClass
{
public static void Do(SPWeb rootWeb)
{
Console.WriteLine(rootWeb.Url);
Console.WriteLine(rootWeb.Title);
}
}
}
"@


Then add the code to the memory and call your code:
#Here you just add the assemblies and the code to the memory
Add-Type -ReferencedAssemblies $referencingassemblies -TypeDefinition $mysource -Language CSharp
#For this sample I will need another assembly
[system.reflection.assembly]::LoadWithPartialName("Microsoft.Sharepoint")
#Load the site-object of your webapp
$site = New-Object Microsoft.SharePoint.SPSite("http://www.mydomain.com")
#Use the rootweb of your site
$root = $site.rootweb
#Overload to your C# method. To call the method use in brakets the namespace and class.
[MyNamespace.MyClass]::Do($root)

In this sample above you already see how to combine powershell code with C# code. If you change something in your C# code, then close the powershell window and re-open, so the code will be loaded/added to memory again. Otherwise you won't see the changes you made.
You can copy the code-segments above into one powershell script file and give it a try.

Keine Kommentare:

Kommentar veröffentlichen