scapegoat17 scapegoat17 - 1 year ago 108
C# Question

Running PowerShell script in a C# Windows Service App

I am really not asking for any specific lines of code here, but more along the lines of someone being able to explain to me the idea of it to help me have a better understanding. I am very new to coding with PowerShell scripts let alone calling them in a C# app. Would anyone be able to explain or even point me in the right direction so I can learn about what I would need to do here. I have a basic "Hello World" script that I would like to call from a C# Windows Service using VS2010. I have seen examples around the internet, but they are very brief and don't really teach the concept behind it.

Any help would be much appreciated!

Answer Source

This is what I was able to get to work for me.

I basically followed the information that I found from this post, but changed a couple of things to get it to work for me: Problem with calling a powershell function from c#

For example, for the ps.AddCommand("BatAvg") I just added my own function in my .ps1 file ps.AddCommand("PS1FunctionName") and didn't add any parameters since it was not necessary. The answer was staring me in the face the whole time, I just didn't know where I needed to place it in my windows service. I was able to figure that out and now I am cruising!

Also, don't forget to reference using System.Management.Automation and using System.Management.Automation.Runspaces in your code (for all the future people that may look at this).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download