Howto start shell application from PowerShell cmdlet/function using C# in Visual Studio 2012

Once again, during a work for a bigger, much bigger, project I’ve developed a little feature that I thought I should share with you girls and boys.

At Microsoft Knowledge Base Article 305369 I found what I used as a base for this coding exercise.

I had the need of launching an application from my PowerShell cmdlet/function and since I do want to use my new knowledge and compile my cmdlets I can’t just use “Start-Process” but must write this in C#. Here is how I did it…

PoShClass Step 04-001

I’ve tried to highlight parts that I think is important and stands out from the link I provided above. What we do is that we create a function on line 45 and 46 called ‘Get-PingFromInfoworksTV’. At line 50 we create an object called pInfo of the ProcessStartInfo class and we continue on line 51 and 52 to specify the command that we want to run and some parameters to that command.

In order to get some output we must enable the feature to redirect so called ‘Standard Output’ or for those of you that tried the (console) “Hello World” project in C, C++ or C# knows that stdout Smile Anyhow, we enable that on line 54.

We actually launch the application/command on line 55 and collect its output on line 56. Later in the while-loop we write it back out.

So why do this? Well, for me I wanted to create a function that computes some variables and then launches an application with those variables as arguments/parameters to that application. More accurate, I wanted to run a setup.exe with parameters that I wasn’t able to foreseen what they would be.

I hope it will come to use!

 

/Tim

Oh and by the way, since “ping” isn’t a GUI application, I had to insert the code on line 53, it worked fine without that line to start “calc” but that application didn’t have and output.

About The Author

Tim Nilimaa is a consultant with Lumagate in Sweden. He has been working with Configuration Manager for 8 years. His knowledge has been selected as a speaker at many events among them Microsoft Management Summit.

No Comments

Leave A Reply