34

I'm trying to execute a Powershell script from an asp.net webpage and I keep getting this error when it tries to execute the script. I have tried 2 methods of executing the script and both give me the same error. The full error is:

An unhandled exception occurred while processing the request PSSnapInException: Cannot load PowerShell snap-in Microsoft.PowerShell.Diagnostics because of the following error: Could not load file or assembly 'C:\source\repos\WebApp\WebApp\Microsoft.PowerShell.Commands'. The system cannot find the file specified.

PowerShell powershell = PowerShell.Create();
            using (Runspace runspace = RunspaceFactory.CreateRunspace())
            {
                runspace.Open();
                powershell.Runspace = runspace;
                System.IO.StreamReader sr = new System.IO.StreamReader("C:\\Desktop\\test.ps1");
                powershell.AddScript(sr.ReadToEnd());
                var results = powershell.Invoke();
                if (powershell.Streams.Error.Count > 0)
                {
                    // error records were written to the error stream.
                    // do something with the items found.
                }
            }
    using (PowerShell PowerShellInstance = PowerShell.Create())
                {   
  PowerShellInstance.AddScript("C:\\Users\\RSpotton\\Desktop\\test.ps1");
                    PowerShellInstance.Invoke();
                }

1 Answer 1

73

I had a similar issue and accompanying error message. Installing the NuGet package for Microsoft.PowerShell.SDK into my project did the trick.

Sign up to request clarification or add additional context in comments.

3 Comments

It would be great if usage of powershell in C# was better documented. thanks BinaryBurnie. In case it helps anyone, found this documented in a github issue as well: github.com/PowerShell/PowerShell/issues/2108
In my case, I had to uninstall this package and install an older version (went from 7.1 to 6.2.7). The other related packages like System.Management.Autoamtion were 6.2.7 as well
For using PowerShell in a unit test project, I also needed to install Microsoft.PowerShell.Commands.Diagnostics NuGet package.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.