'Powershell script not running in .net core api deployed in IIS
I have a .net core api deployed on IIS on a Windows server. This api is executing a powershell command (command is updating a text file and also restarting a windows service). Whenever I am running the code using VS on my local machine or running the same code using VS in the windows server where api is deployed, the powershell command is executing fine. But whenever I am deploying the same changes on IIS and then hitting the api, the same powershell command is not executing and also I am not seeing any exception.
Below is my code through which I am executing the powershell command in the api code.
public async Task SaveCredentials()
{
List<Credential> ls = new List<Credential>();
Credential c1 = new Credential();
c1.Username = "username1";
c1.Password = "8407EC85-3E02-4CED-922F-893A3676786F";
Credential c2 = new Credential();
c2.Username = "username2";
c2.Password = "C6BC830C-570D-429C-BD5E-AE521FDBC952";
Credential c3 = new Credential();
c3.Username = "username3";
c3.Password = "63724EDC-C392-4D69-ADD5-5D5075CD4DA2";
ls.Add(c1);
ls.Add(c2);
ls.Add(c3);
if (ls.Count > 0)
{
var usernames = new string[ls.Count];
var passwords = new string[ls.Count];
foreach (var item in ls)
{
int index = ls.IndexOf(item);
usernames[index] = item.Username;
passwords[index] = item.Password;
}
InitialSessionState initialSessionState = InitialSessionState.CreateDefault();
initialSessionState.ExecutionPolicy = ExecutionPolicy.Unrestricted;
using (Runspace rs = RunspaceFactory.CreateRunspace())
{
rs.Open();
using (PowerShell powershell = PowerShell.Create())
{
var scriptPath = $@"{AppContext.BaseDirectory}Powershell\pscommand.ps1";
powershell.Runspace = rs;
// specify the script code to run.
powershell.AddScript(File.ReadAllText(scriptPath));
// specify the parameters to pass into the script.
powershell.AddParameter("Username", usernames);
powershell.AddParameter("Password", passwords);
var pipelineObjects = await powershell.InvokeAsync().ConfigureAwait(false);
// print the resulting pipeline objects to the console.
foreach (var item in pipelineObjects)
{
_logger.LogInformation(item.BaseObject.ToString());
}
}
// Close the runspace and release any resources.
rs.Close();
}
}
}
Can someone help me here or give some guidance?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
