I am using System.Management.Automation.dll to execute powershell script from c# code.
Following is my c# code
public void Execute()
{
using (var runspace = RunspaceFactory.CreateRunspace())
{
try
{
var script = File.ReadAllText("script.ps1");
runspace.Open();
var ps = PowerShell.Create();
ps.Runspace = runspace;
ps.Commands.AddScript(script);
//ps.Ad
ps.Invoke();
foreach (var result in ps.Invoke())
{
Console.WriteLine(result);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
powershell script is
logparser "SELECT top 1 *,null INTO iisLogs FROM 'D:\u_ex200621\*.log' where date >= '2020-01-01' " -i:iisw3c -o:SQL -server:172.29.182.160 -database:DBA_Work -username:azuredev -password:cybage@123 -transactionRowCount:10000 -createTable: OFF
I have added logparser.dll path to Environment Variable so I can execute it from anywhere on machine.
But I tried to execute above code it did not execute anything.Same script I tried using Power shell then it works perfectly.
Please let me know correct way to execute powershell script using C# code.I tried multiple solutions on stackoverflow but no luck.