How to Run C# Code from PowerShell?
Some time back, I wrote C# code for SharePoint Administration Governance purpose: Find Large Lists & Generate Report in SharePoint , which actually scans all lists in all sites and creates a report in CSV format.
I feel PowerShell is more convenient than C# for couple of reasons:
- Because, PowerShell is quite powerful and more flexible administration and automation tool
- Although C# is good for typical Software development, for such small tasks C# project is overkill!
- Its faster to write, deploy and change it in PowerShell than creating a project in Visual Studio, compiling it, deploying it to the target, correcting the code, compiling it again, deploying it again!
So, I wanted to leverage the existing C# code. While the code is relatively simpler to rewrite in PowerShell, Found another interesting way to run C# code in PowerShell. Here is an example:
#Assemblies to Reference
$Assembly = (
"Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" ,
"Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
);
# C# Source Code
$SourceCode = @"
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.IO;
namespace SPGovernance
{
public class AdminReports
{
public static void GenerateLargeListsReport(string siteCollURL)
{
SPSite site = new SPSite(siteCollURL);
StreamWriter SW;
//Enumerate through each sub-site
foreach (SPWeb web in site.AllWebs)
{
foreach (SPList list in web.Lists)
{
if (list.ItemCount > 2000)
{
//Log the details to a file
SW = File.AppendText("c:\\LargeListsInfo.csv");
SW.WriteLine(list.Title + "," + web.Url + list.DefaultViewUrl + "," + list.ItemCount);
SW.Close();
}
}
}
Console.WriteLine("Large Lists Reports has been Generated!");
}
}
}
"@
#Add the Assembly
Add-Type -ReferencedAssemblies $Assembly -TypeDefinition $SourceCode -Language CSharp
#Call the function from Assembly
[SPGovernance.AdminReports]::GenerateLargeListsReport("https://sharepoint.crescent.com/sites/Sales")
One limitation is: You may get “Add-Type : Cannot add type. The type name ‘SPGovernance.AdminReports’ already exists” error message if you try to execute the code more than once. This is a known limitation and you have to launch a new PowerShell window and execute the code.
man you rock