Example #1
0
        public static bool Execute(string script, IDictionary @params, ref string output)
        {
            using (Runspace rs = RunspaceFactory.CreateRunspace())
            {
                rs.Open();

                using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
                {
                    ps.Runspace = rs;

                    ps.AddScript(script);
                    ps.AddParameters(@params);

                    var outputs = ps.Invoke();
                    var errors  = ps.Streams.Error;

                    if (errors.Count > 0)
                    {
                        output += string.Join(Environment.NewLine, errors.Select(e => e.ToString()));
                        return(false);
                    }

                    output += string.Join(Environment.NewLine, outputs.Select(o => o.BaseObject.ToString()));

                    return(true);
                }
            }
        }
Example #2
0
        protected Collection <T> RunScript <T>(string cmdletName, Dictionary <string, object> scriptParameters)
        {
            // specify the script code to run.
            _pwrSh.AddCommand(cmdletName);
            // specify the parameters to pass into the script.
            _pwrSh.AddParameters(scriptParameters);
            // execute the script and await the result.
            Collection <T> results = _pwrSh.Invoke <T>();

            // Reset for next
            _pwrSh.Commands.Clear();

            return(results);
        }