Search code examples
c#powershellrunspace

Run Powershell from C#


I need to start a powershell script from C# and get the PSSSecurityException on pipeline.Invoke()

AuthorizationManager check failed.

My code:

RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
{
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    Command scriptCommand = new Command(scriptfile);
    pipeline.Commands.Add(scriptCommand);
    pipeline.Invoke();
}

Questions

  1. I suspect that I need to set PSCredential. But I can not promt for it, so I have to handle this in code. Can this be done in a secure way? (This was not the case)

Solution

  • The problem was that the script was placed on a share. To run scripts on this share I needed to add the share to Trusted Sites.

    enter image description here

    enter image description here