Using PowerShell in your C# code

SharePoint standard comes with a lot of cmdlets ready for use. Sometimes it might be handy to be able to use those cmdlets in your serverside code. For instance, using Merge-SPLogFile to combine the logs from all the servers into one single file.

To start using PowerShell inside your C# code, add a reference to the System.Management.Automation.dll library.

add reference

You can find it under: C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0

At the using section of your code page add:

using System.Management.Automation;
using System.Management.Automation.Runspaces;

Now it’s time to start creating our PowerShell objects. It’s important to load the Microsoft.SharePoint.PowerShell dll, otherwise we’re unable to execute any SharePoint cmdlets. Do so by using the following codeblock:

InitialSessionState iss = InitialSessionState.CreateDefault();
PSSnapInException warning;
iss.ImportPSSnapIn("Microsoft.SharePoint.PowerShell", out warning);

After we created our sessionstate, we need a runspace where we can execute pipelines:

Runspace runspace = RunspaceFactory.CreateRunspace(iss);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();

The next step is building the command to be executed by PowerShell. We have to specify a path for storing the merged log file. By using the temporary folder, and a guid for the name of the file, we can assume that there will be no conflicts. If the file already exists, the -OverWrite parameter will make overwrite the existing merged log. It’s always possible to add more parameters to the Merge-SPLogFile cmdlet.

string savePath = String.Format("{0}{1}.log", System.IO.Path.GetTempPath(), System.Guid.NewGuid().ToString());
string command = String.Format("Merge-SPLogFile -OverWrite -Path '{0}'", savePath);

By adding our script, and invoking our pipeline, we let PowerShell do its thing.

pipeline.Commands.AddScript(command);
try
{
    pipeline.Invoke();
}
catch (Exception ex)
{
    throw ex;
}

Now that we’re ready with the PowerShell execution it’s time to close things up.

runspace.Close();

That’s it! Now if you put everything in your codefile and let it run, you should find a merged log file at your temporary location (C:\Users\AppData\Local\Temp) with a “guid”.log

If you wish to clean up your temporary file after working with it you can use the following method:

System.IO.File.Delete(savePath);

I’ve implemented this method in a solution I created. You can find it at codeplex, and here’s a direct link to the sourcecode where I use this code.

Advertisements

2 thoughts on “Using PowerShell in your C# code

  1. Am getting an error in the below line when i excute it
    iss.ImportPSSnapIn(“Microsoft.SharePoint.PowerShell”, out warning); error:- the Microsoft.Sharepoint.Powerhsell is not installed in ur machine can you help on this

    1. Make sure your application you’re developping is scoped to 64 bit. If this is already the case make sure your server has PowerShell installed. If this is also already ok, do the following steps:

      • Open a command prompt with elevated permissions.
      • Browse to C:\Windows\Microsoft.NET\Framework64\v2.0.50727
      • Execute the InstallUtil.exe with the following command line parameters:
        InstallUtil /LogToConsole=true C:\Windows\assembly\GAC_MSIL\Microsoft.SharePoint.PowerShell\14.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Powershell.dll

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s