0

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.

17
  • 1
    Where is "script.ps1" located? Is it in the same folder and the c# executable? Use full path name of the script file. Commented Jul 5, 2020 at 15:44
  • Yes,It is in same folder. Commented Jul 5, 2020 at 16:21
  • Thanks, It worked.I tried many solutions but didn't tried this running VS in admin. you saved my day. Commented Jul 5, 2020 at 18:14
  • Running the exe outside of VS will also work. Commented Jul 5, 2020 at 21:28
  • Hi, I installed windows service on server and there it is again not running. I change execution policy to unrestricted but no luck.Can you please me Commented Jul 6, 2020 at 9:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.