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();
}
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.
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.
I had a similar issue and accompanying error message. Installing the NuGet package for Microsoft.PowerShell.SDK
into my project did the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With