I'm unable to Run powershell script from Asp.net core mvc
Error: System.Management.Automation.PSSecurityException: 'File C:\Anand\VS_Projects\FieldService\FieldService\wwwroot\Script_Files\ClearSpaceScript.ps1 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 able to run this script file in this pc in Powershell ISE, but ASP.net is unable to run scripts.
This is my code:
//Running Script
String r = "";
string SCRIPT_PATH = @"C:\Anand\VS_Projects\FieldService\FieldService\wwwroot\Script_Files\" + script.Location;
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
//create a pipeling and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("Set-ExecutionPolicy Remote-Signed -Scope Process");
Command command = new Command(SCRIPT_PATH);
//Adding Parameters to the Powershell Script
if (script.isUsername)
{
command.Parameters.Add("username", username);
}
if (script.isPassword)
{
command.Parameters.Add("password", runScriptModel.Password);
}
if (script.isUserPCName)
{
command.Parameters.Add("pcname", runScriptModel.Hostname);
}
pipeline.Commands.Add(command);
//Running
try
{
var result = pipeline.Invoke();
if (pipeline.HadErrors)
{
var pipelineErrors = pipeline.Error.ReadToEnd();
foreach (var error in pipelineErrors)
{
r = r + "@" + error.ToString();
}
r = r.Replace("@", System.Environment.NewLine);
return Json(new
{
success = false,
responseText = r
});
}
foreach (var res in result)
{
r = r + "@" + res.ToString();
}
r = r.Replace("@", System.Environment.NewLine);
return Json(new
{
success = true,
responseText = "Script finished Running",
result = r
});
}
catch (Exception ex)
{
ViewBag.Result = ex.Message;
return Json(new
{
success = false,
responseText = ex.Message
});
}