rukiman
rukiman

Reputation: 643

Invoking powershell script within c# that calls another powershell script is throwing an UnauthorizedAccessException

The function below works well for my test

    private static void RunScript(string scriptText)
    {
        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();
    }

I call this function like so

RunScript(File.ReadAllText("test.ps1"));

All is good. Now I have modified test.ps1 to call other powershell script.

But now I get an exception when I run this.

UnauthorizedAccessException: cannot be loaded because running scripts is disabled on this system. For more information, see 
about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.

I'm guessing I need to set execution policy to "bypass". How can I set this?

Also is there a way to provide the powershell script filename into the Pipeline object instead of the contents of the script file?

Upvotes: 0

Views: 398

Answers (1)

rukiman
rukiman

Reputation: 643

OK after experimenting, figured out I can simply call my function multiple times. Once to set the policy and next time to call any scripts. The policy seems like it is set after just one call.

RunScript("Set-ExecutionPolicy -Scope Process -ExecutionPolicy ByPass");
RunScript(File.ReadAllText("test.ps1"));

private static void RunScript(string scriptText)
{
    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();
}

You can also queue commands i.e

private static void RunScript(string scriptText)
{
    Runspace runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript("Set-ExecutionPolicy -Scope Process -ExecutionPolicy ByPass");
    pipeline.Commands.AddScript(scriptText);
    pipeline.Commands.Add("Out-String");
    Collection<PSObject> results = pipeline.Invoke();
    runspace.Close();
}

Upvotes: 0

Related Questions