Reputation: 5841
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! Thanks!
Upvotes: 0
Views: 7234
Reputation: 5841
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).
Upvotes: 1
Reputation: 3451
Here is a pretty good discussion on how to call Powershell from C#: http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C
I suggest you start with the RunScript function and add it to a VS2010 console application. Main() would then invoke RunScript something like RunScript( "echo 'hello from PS';get-date; get-culture; ")
.
Windows services have quite a few differences from a normal console application. You can read about how to write a windows service on MSDN, but if you've never coded before, you have a steep learning curve in front of you.
There is a service from an old Resource Kit call srvany.exe (Google it) which would run any console app as a service. However in Windows Vista (and above) services were restricted from accessing the desktop, so srvany could only be successful in Vista and above if you EXE doesn't need keyboard input or need to write to the display. However your EXE could read/write files.
Upvotes: 1