using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Text; namespace OpenIdProvider.Shared { public class PowerShellInvoker : IDisposable { private readonly Runspace _runspace; private readonly RunspaceInvoke _invoker; public PowerShellInvoker(params string[] modules) { var iss = InitialSessionState.CreateDefault(); iss.ImportPSModule(modules); iss.ThrowOnRunspaceOpenError = true; _runspace = RunspaceFactory.CreateRunspace(iss); _runspace.Open(); _invoker = new RunspaceInvoke(_runspace); } public ICollection ExecuteScript(string scriptText) { return _invoker.Invoke(scriptText).ToList(); } public ICollection ExecuteCommand(string cmdlet, object parameters = null) { using (var pipeline = _runspace.CreatePipeline()) { var cmd = new Command(cmdlet); if (parameters != null) { foreach (var property in parameters.GetType().GetProperties()) { cmd.Parameters.Add(property.Name, property.GetValue(parameters, null)); } } pipeline.Commands.Add(cmd); var result = pipeline.Invoke(); if (pipeline.Error.Count > 0) { var psError = (PSObject) pipeline.Error.Read(); var error = (ErrorRecord) psError.BaseObject; throw error.Exception; } return result.ToList(); } } public void SetVariable(string name, object value) { _runspace.SessionStateProxy.SetVariable(name, value); } #region Implementation of IDisposable public void Dispose() { if (_invoker != null) { _invoker.Dispose(); } if (_runspace != null) { _runspace.Close(); _runspace.Dispose(); } } #endregion } }