SharePoint Dragons

Nikander & Margriet on SharePoint

Appreciating a simple idea about running PowerShell Scripts from SharePoint

It’s a simple idea to want to be able to execute PowerShell scripts from code, as you can see in http://social.technet.microsoft.com/Forums/en-US/sharepointdevelopment/thread/318429d9-fc63-479b-a20a-62883c9132fa. The code is something similar to this:

PowerShell ps = PowerShell.Create();

string scriptText = “Add-PSSnapin Microsoft.SharePoint.Powershell Enable-SPFeature -Identity PublishingSite -URL ” + siteAddress + ” -Force”;

Runspace runspace = RunspaceFactory.CreateRunspace();

runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();

pipeline.Commands.AddScript(scriptText);

pipeline.Commands.Add(“Out-String”);

Collection<PSObject> results = pipeline.Invoke();

runspace.Close();

StringBuilder stringBuilder = new StringBuilder();

foreach (PSObject obj in results)

{

stringBuilder.AppendLine(obj.ToString());

}

return stringBuilder.ToString();

}

In the blog post http://blog.karstein-consulting.com/2011/08/04/sharepoint-powershell-timer-jobs-run-powershell-scripts-in-sharepoint-timer-service-context/ this idea is taken to the next level by allowing you to run PowerShell scripts in the SharePoint Timer Service context. Really useful, and elegantly done!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

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

Facebook photo

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

Connecting to %s

%d bloggers like this: