6

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.

3
  • what is the error? try wrapping it with a try-catch block. Commented Apr 8, 2018 at 12:16
  • There is no error, it isn't enables the 3.5 feature. After a few seconds the console says "finished" Commented Apr 8, 2018 at 12:21
  • 2
    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. Commented Apr 8, 2018 at 14:28

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.