Quantcast
Channel: Bram Nuyts » Merge-SPLogFile
Viewing all articles
Browse latest Browse all 2

Using PowerShell in your C# code

$
0
0

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.



Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images