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.
Author by
Bad-Ass
Updated on June 19, 2022Comments
-
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 about 6 yearswhat is the error? try wrapping it with a try-catch block.
-
Bad-Ass about 6 yearsThere is no error, it isn't enables the 3.5 feature. After a few seconds the console says "finished"
-
Patrick Meinecke about 6 yearsCheck
PowerShellInstance.HadErrors
. If that's true, checkPowerShellInstance.InvocationStateInfo.Reason
for the exception, if that's null checkPowerShellInstance.Streams.Error
for non-terminating error records. If none of those give the information you needPowerShellInstance.EndInvoke(result)
will give the output of the command.
-