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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With