views:

339

answers:

3

The Sys Admin guy is writing some common housekeeping Power Shell scripts. Predominantly for AD management (updating exchange details, moving people around security groups etc.)

I'd like to use these scripts from C# (I intend to write it as a library, consumed by a web site).

I've seen this code project article which looks interesting and a good place to start.

Does anyone have any experience of Power Shell interop? Can anyone think of any major gotchas before I jump head first into a spike?

Extra Information:

I appreciate there are logistical challenges particularly with CI and versioning.

The plan was initially to use Directory Services, exposing services through a web API and CmdLets. Unfortunately we’re having difficulties with Directory Services (e.g. truncated results for large sets).

In the meanwhile, rather than use an inconsistent mix, I figured I should investigate using the Sys Admins’ scripts. Why re-invent the wheel?

I’ve already written my domain model. I intend to implement the repository pattern so I can abstract out AD / Exchange integration allowing different implementations in the future.

+1  A: 

I don't think there are many Gotchas to this approach over the usual problems of running a script from a compiled program. I find the biggest problems tend to be

  1. Keeping people from moving the script
  2. Making sure people don't add hidden dependencies in the script that are not reflected in the calling program.

But I do think you should consider another model for your development. Instead of having a program reference a script, why not add all of the logic into a compiled library. This can be easily linked into the program and exposed to PowerShell via a CmdLet. I find this is an easier way to maintain shared code between scripts in programs.

JaredPar
+1  A: 

I've spent the last few months running PowerShell code from insite a C# application and it works fine, you can do some pretty interesting stuff with it. That said as JaredPar mention having the PowerShell script in script files outside the app can be a pain. I have all my PowerShell code in a library and ship that around to where its needed and it works well.

Sam Cogan
+1  A: 

If the scripts have dependencies on system or user profile, then you will need to explicitly dot-source the profile into your runspace first.

Higher levels of control (e.g. session carried from one command to another, ... accessing debug output) require more advanced/low-level/complex work.

Other than that, it all just works.

Richard
Richard, I don't know what you mean by dot-source the profile. Could you expand at all please?
Ed Blackburn
". PSscript" to include contents of script file into the current scope as is done with the profile files.
Richard