Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run powershell scripts from c#

Tags:

c#

powershell

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.

like image 425
Bad-Ass Avatar asked Apr 08 '18 12:04

Bad-Ass


1 Answers

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.

like image 128
Aspram Avatar answered Oct 10 '22 04:10

Aspram