I've been trying to execute my powershell code from a button click on a SharePoint Webpart. I came across this solution on a forum post.

private string RunScript(string scriptText){

Runspace runspace = RunspaceFactory.CreateRunspace();

// open it

runspace.Open(); //This is where it errors out.

// create a pipeline and feed it the script text

Pipeline pipeline = runspace.CreatePipeline();

// add an extra command to transform the script
// output objects into nicely formatted strings

// remove this line to get the actual objects
// that the script returns. For example, the script

// "Get-Process" returns a collection
// of System.Diagnostics.Process instances.


// execute the script

Collection<psobject /> results = pipeline.Invoke();

// close the runspace


// convert the script result into a single string

StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)

return stringBuilder.ToString();}    

Run Powershell Script from Sharepoint page

I've added the code from the above post to a Webpart solution but i keep running into the following error on the runspace.Open() line.

System.Security.SecurityException was unhandled by user code HResult=-2146233078 Message=Requested registry access is not allowed. Source=mscorlib StackTrace: at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable) at System.Environment.GetEnvironmentVariable(String variable, EnvironmentVariableTarget target) at System.Management.Automation.ModuleIntrinsics.GetExpandedEnvironmentVariable(String name, EnvironmentVariableTarget target) at System.Management.Automation.ModuleIntrinsics.SetModulePath() at System.Management.Automation.ExecutionContext.InitializeCommon(AutomationEngine engine, PSHost hostInterface) at System.Management.Automation.AutomationEngine..ctor(PSHost hostInterface, RunspaceConfiguration runspaceConfiguration, InitialSessionState iss) at System.Management.Automation.Runspaces.LocalRunspace.DoOpenHelper() at System.Management.Automation.Runspaces.RunspaceBase.CoreOpen(Boolean syncCall) at TestWebPart.Project.Project.ExecuteCode_Click(Object sender, EventArgs e) at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) InnerException:

I've tried running the code under an impersonation block but that didn't seem to help.

Any ideas/suggestions on fixing this error will be greatly appreciated.

1 Answer 1




to get privileges

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.