Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C# to execute PowerShell script with command line args using V2 methods

I am writing an C# application which will need to execute Powershell scripts with command line arguments and retrieve the output (aka what I would expect to see in the output window of PowerShell ISE - including exception information)

I have found numerous code examples of how to accomplish this task using PowerShell V1 objects. These examples create runspaces, pipelines, etc. (ex Execute PowerShell Script from C# with Commandline Arguments)

I have seen a few scant references to a different way to do this using PowerShell V2. (the top answer here: Capturing Powershell output in C# after Pipeline.Invoke throws) Using V2 seems much simpler. No messing around with runspaces, piplines or any of that. Something like this:

PowerShell powerShell = PowerShell.Create();

powerShell.AddScript(script);
var results = powerShell.Invoke();

Are there any good working examples out there of using PowerShell V2 objects to execute scripts from within C# code? Is there any known good documentation of the PowerShell V2 (or even V3) objects and best practices on how to use them? Offical docs from Microsoft like there ought to be? A good book or site which breaks down the System.Management.Automation assembly piece by piece?

like image 965
Derek Evermore Avatar asked Jul 25 '13 19:07

Derek Evermore


People also ask

What does %d do in C?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.

What does %C do in C?

Show activity on this post. %d is used to print decimal(integer) number ,while %c is used to print character . If you try to print a character with %d format the computer will print the ASCII code of the character.

Is C useful now?

C is worth learning in 2022 because it is easy to grasp. It gives you basic knowledge about the inner workings of computer systems and the core concepts that drive programming.


1 Answers

Answering my own question here. It looks like the right approach would be for my application to function as a PowerShell Host

https://msdn.microsoft.com/en-us/library/ee706563(v=vs.85).aspx

Use of PowerShell V2 objects is defined here: http://msdn.microsoft.com/en-us/library/windows/desktop/system.management.automation.powershell(v=vs.85).aspx

like image 103
Derek Evermore Avatar answered Oct 13 '22 01:10

Derek Evermore