Run powershell scripts from c#

11,537

Try to add admin privileges into your powershell script, sometimes that helps

PowerShell.exe -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -windowstyle hidden -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -noexit -File "$ScriptPath"' -Verb RunAs}"

You can save your powershell command in ps1 file and give the path as a parameter ($ScriptPath). This powershell command is tested on C# via running your specified code. Hope this helps. If not then I advice to use Process from C# System.Diagnostics namespace.

Share:
11,537
Bad-Ass
Author by

Bad-Ass

Updated on June 19, 2022

Comments

  • Bad-Ass
    Bad-Ass almost 2 years

    I am trying to write a powershell script with c# in my app. the problem is the the script doesn't do the job if I run it with c#, but it does the work if I run it by hand.

    That's the script: DISM /online /Enable-Feature /Featurename:NetFx3 /All

    The script enables Framwork 3.5 on windows server. Source

    My code:

    NuGet: System.Management.Automation

    using (PowerShell PowerShellInstance = PowerShell.Create()) 
    { 
        PowerShellInstance.AddScript("DISM /online /Enable-Feature /Featurename:NetFx3 /All ");
    
        // begin invoke execution on the pipeline
        IAsyncResult result = PowerShellInstance.BeginInvoke();
    
        // do something else until execution has completed.
        // this could be sleep/wait, or perhaps some other work
        while (result.IsCompleted == false)
        {
            Console.WriteLine("Waiting for pipeline to finish...");
            Thread.Sleep(1000);
    
            // might want to place a timeout here...
        }
    
        Console.WriteLine("Finished!");
    }
    

    I used examples from Here

    Note: my app run as admin.

    • Daniel
      Daniel about 6 years
      what is the error? try wrapping it with a try-catch block.
    • Bad-Ass
      Bad-Ass about 6 years
      There is no error, it isn't enables the 3.5 feature. After a few seconds the console says "finished"
    • Patrick Meinecke
      Patrick Meinecke about 6 years
      Check PowerShellInstance.HadErrors. If that's true, check PowerShellInstance.InvocationStateInfo.Reason for the exception, if that's null check PowerShellInstance.Streams.Error for non-terminating error records. If none of those give the information you need PowerShellInstance.EndInvoke(result) will give the output of the command.