Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix error "Cannot load PowerShell snap-in Microsoft.PowerShell.Diagnostics because of the following error: Could not load file or assembly"

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();
                }
like image 876
Riley Spotton Avatar asked Jul 23 '19 14:07

Riley Spotton


People also ask

How do I see PowerShell errors?

You can use Get-Error to display a specified number of errors that have occurred in the current session using the Newest parameter. The Get-Error cmdlet also receives error objects from a collection, such as $Error , to display multiple errors from the current session.

What is Windowspowershell?

Windows PowerShell is a powerful tool for automating tasks and simplifying configuration and can be used to automate almost any task in the Windows ecosystem, including active directory and exchange. It's no wonder that it's become a popular tool among sysadmins and experienced Windows users.


1 Answers

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

like image 95
BinaryBurnie Avatar answered Sep 16 '22 11:09

BinaryBurnie