How to run a PowerShell script from C# as non-elevated user How to run a PowerShell script from C# as non-elevated user powershell powershell

How to run a PowerShell script from C# as non-elevated user


We use a version of the below. The "script" parameter is the PS script to run. We use this from a custom command line so that we can mix c# commands with some written in PS. "results" can be used to capture the evaluation of your script. The "out-default" line means that the output of the PS script is written to the console. A version of this can instead capture the output to a TextBox or similar if you have a WinForm of WPF app.

public void run(string script){    IEnumerable<PSObject> results;    var config = RunspaceConfiguration.Create();    var host = new ScriptHost();    using (var runspace = RunspaceFactory.CreateRunspace(host, config))    {        runspace.Open();        runspace.SessionStateProxy.SetVariable("prog", this);        using (var pipeline = runspace.CreatePipeline())        {            if (!string.IsNullOrEmpty(scriptPath))                pipeline.Commands.AddScript(string.Format("$env:path = \"{0};\" + $env:path", scriptPath));            pipeline.Commands.AddScript(script);            var outDefault = new Command("out-default");            outDefault.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);            pipeline.Commands.Add(outDefault);            results = pipeline.Invoke();        }    }}


more on lkaso answer

this shows you how to run it as anybody, not just admin. YOu have to run it as somebody, the service is running as a heavily restricted account that cannot do anything.

or run the service itself as joe user


Can you use SysInternals procmon tool to see what Registry access it's trying to accomplish? Maybe that will give you some insight as to what you could do to solve the problem.