public PSTestScope(bool connect = true)
        {
            SiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"];
            CredentialManagerEntry = ConfigurationManager.AppSettings["SPOCredentialManagerLabel"];

            var iss = InitialSessionState.CreateDefault();
            if (connect)
            {
                SessionStateCmdletEntry ssce = new SessionStateCmdletEntry("Connect-SPOnline", typeof(ConnectSPOnline), null);

                iss.Commands.Add(ssce);
            }
            _runSpace = RunspaceFactory.CreateRunspace(iss);

            _runSpace.Open();

            if (connect)
            {
                var pipeLine = _runSpace.CreatePipeline();
                Command cmd = new Command("connect-sponline");
                cmd.Parameters.Add("Url", SiteUrl);
                if (!string.IsNullOrEmpty(CredentialManagerEntry))
                {
                    cmd.Parameters.Add("Credentials", CredentialManagerEntry);
                }
                pipeLine.Commands.Add(cmd);
                pipeLine.Invoke();
            }
        }
Esempio n. 2
0
        public PSTestScope(bool connect = true)
        {
            SiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"];
            CredentialManagerEntry = ConfigurationManager.AppSettings["SPOCredentialManagerLabel"];
            Realm = ConfigurationManager.AppSettings["Realm"];
            AppId = ConfigurationManager.AppSettings["AppId"];
            AppSecret = ConfigurationManager.AppSettings["AppSecret"];

            var iss = InitialSessionState.CreateDefault();
            if (connect)
            {
                SessionStateCmdletEntry ssce = new SessionStateCmdletEntry("Connect-PnPOnline", typeof(ConnectOnline), null);

                iss.Commands.Add(ssce);
            }
            _runSpace = RunspaceFactory.CreateRunspace(iss);

            _runSpace.Open();

            // Sets the execution policy to unrestricted. Requires Visual Studio to run in elevated mode.
            var pipeLine = _runSpace.CreatePipeline();
            Command cmd = new Command("Set-ExecutionPolicy");
            cmd.Parameters.Add("ExecutionPolicy", "Unrestricted");
            cmd.Parameters.Add("Scope", "Process");
            pipeLine.Commands.Add(cmd);
            pipeLine.Invoke();

            if (connect)
            {
                pipeLine = _runSpace.CreatePipeline();
                cmd = new Command("connect-pnponline");
                cmd.Parameters.Add("Url", SiteUrl);
                if (!string.IsNullOrEmpty(CredentialManagerEntry))
                {
                    // Use Windows Credential Manager to authenticate
                    cmd.Parameters.Add("Credentials", CredentialManagerEntry);
                }
                else
                {
                    if (!string.IsNullOrEmpty("AppId") && !string.IsNullOrEmpty("AppSecret"))
                    {
                        // Use oAuth Token to authenticate
                        if (!string.IsNullOrEmpty(Realm))
                        {
                            cmd.Parameters.Add("Realm", Realm);
                        }
                        cmd.Parameters.Add("AppId", AppId);
                        cmd.Parameters.Add("AppSecret", AppSecret);
                    }
                }
                pipeLine.Commands.Add(cmd);
                pipeLine.Invoke();
            }
        }
        public void InitializeTests()
        {

            RunspaceConfiguration config = RunspaceConfiguration.Create();
            
            PSSnapInException warning;

            config.AddPSSnapIn("ShareFile", out warning);

            runspace = RunspaceFactory.CreateRunspace(config);
            runspace.Open();

            // do login first to start tests
            using (Pipeline pipeline = runspace.CreatePipeline())
            {

                Command command = new Command("Get-SfClient");
                command.Parameters.Add(new CommandParameter("Name", Utils.LoginFilePath));

                pipeline.Commands.Add(command);

                Collection<PSObject> objs = pipeline.Invoke();
                Assert.AreEqual<int>(1, objs.Count);
                sfLogin = objs[0];
            }
        }
Esempio n. 4
0
        private bool createRunspace(string command)
        {
            bool result = false;
            
            // 20131210
            // UIAutomation.Preferences.FromCache = false;
            
            try {
                testRunSpace = null;
                testRunSpace = RunspaceFactory.CreateRunspace();
                testRunSpace.Open();
                Pipeline cmd =
                    testRunSpace.CreatePipeline(command);
                cmd.Invoke();
                result = true;
            }
            catch (Exception eInitRunspace) {

                richResults.Text += eInitRunspace.Message;
                richResults.Text += "\r\n";
                result = false;
            }
            return result;
            //Screen.PrimaryScreen.Bounds.Width
        }
Esempio n. 5
0
        public PipelineExecutor(Runspace runSpace, string command)
        {
            this.pipeline = runSpace.CreatePipeline(command);
            this.pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);

            this.pipeline.Output.DataReady += this.OutputDataReady;
            this.pipeline.Error.DataReady += this.ErrorDataReady;
        }
        void run_set_host_command(Runspace configuredRunspace, string hostName, string address, string hostsFile)
        {
            using (var command = configuredRunspace.CreatePipeline(
                string.Format("set-HostsFileEntry {0} {1} -f \"{2}\"", hostName, address, hostsFile)))
            {
                var results = command.Invoke();

                expect(() => results.Count() == 0);
            }
        }
 public static ExternalScriptInfo MakeExternalScriptInfo(Runspace powershellRunspace, string exampleScriptName)
 {
     var outputDirectory = new Uri(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase)).LocalPath;
     var exampleScriptPath = Path.Combine(outputDirectory, "ExampleScripts\\" + exampleScriptName + ".ps1");
     var cmd = string.Format("Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned; Get-Command \"{0}\"", exampleScriptPath);
     using (Pipeline pipeline = powershellRunspace.CreatePipeline(cmd))
     {
         var results = pipeline.Invoke();
         return results.First().BaseObject as ExternalScriptInfo;
     }
 }
        public void InitializeTests()
        {
            RunspaceConfiguration config = RunspaceConfiguration.Create();

            PSSnapInException warning;

            config.AddPSSnapIn("ShareFile", out warning);

            runspace = RunspaceFactory.CreateRunspace(config);
            runspace.Open();

            // do login first to start tests
            using (Pipeline pipeline = runspace.CreatePipeline())
            {

                Command command = new Command("Get-SfClient");
                command.Parameters.Add(new CommandParameter("Name", Utils.LoginFilePath));

                pipeline.Commands.Add(command);

                Collection<PSObject> psObjects = pipeline.Invoke();
                Assert.AreEqual<int>(1, psObjects.Count);
                sfLogin = psObjects[0];
            }

            using (Pipeline pipeline = runspace.CreatePipeline())
            {
                Command command = new Command("New-PSDrive");
                command.Parameters.Add("Name", Utils.ShareFileDriveLetter);
                command.Parameters.Add("PSProvider", "ShareFile");
                command.Parameters.Add("Root", "/");
                command.Parameters.Add("Client", sfLogin);

                pipeline.Commands.Add(command);

                Collection<PSObject> psObjects = pipeline.Invoke();

                // Drive is successfully mapped to root folder
                Assert.AreEqual<int>(1, psObjects.Count);
            }
        }
 public PowerShellRunner()
 {
     var psHost = new PSHost(new PSHostUserInterface(this)); 
     runSpace = RunspaceFactory.CreateRunspace(psHost);
     runSpace.Open();
     // Allows scripts to be run for this process
     using (var pipeline = runSpace.CreatePipeline())
     {
         pipeline.Commands.AddScript("Set-ExecutionPolicy -ExecutionPolicy unrestricted -Scope Process -Force");
         pipeline.Invoke();
     }
 }
Esempio n. 10
0
        public static string Execute(bool logErrors, Action<string> onErrorHandler, TestHostUserInterface ui,
                                     params string[] statements)
        {
            if (logErrors)
            {
                ui.OnWriteErrorLineString = onErrorHandler ?? (s => ui.Log.Append(s));
            }

            TestHost host = new TestHost(ui);
            // use public static property, so we can access e.g. the ExecutionContext after execution
            LastUsedRunspace = CreateRunspace(host);
            LastUsedRunspace.Open();
            _doExit = false;
            LastExitCode = null;

            foreach (var statement in statements)
            {
                if (_doExit)
                {
                    break;
                }
                using (var currentPipeline = LastUsedRunspace.CreatePipeline())
                {
                    currentPipeline.Commands.AddScript(statement, false);
                    currentPipeline.Commands.Add("Out-Default");
                    try
                    {
                        currentPipeline.Invoke();
                    }
                    catch (Exception e)
                    {
                        ui.WriteErrorLine(e.ToString());
                    }
                    // pipeline might failed, write errors to ui
                    if (currentPipeline.PipelineStateInfo.State.Equals(PipelineState.Failed))
                    {
                        foreach (var error in currentPipeline.Error.ReadToEnd())
                        {
                            ui.WriteErrorLine(error.ToString());
                        }
                    }
                }
            }

            return ui.Log.ToString();
        }
Esempio n. 11
0
        private static string RunScript(Runspace runspace)
        {
            runspace.Open();
            var pipeline = runspace.CreatePipeline();

            var runspaceInvoke = new RunspaceInvoke(runspace);
            runspaceInvoke.Invoke("Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process -Force");

            pipeline.Commands.AddScript(@"D:\Projekt\EPiServer\SampleCode\CodeSample\ScheduledJobs\SampleScript.ps1");
            pipeline.Commands.Add("Out-String");

            var stringBuilder = new StringBuilder();
            foreach (var psObject in pipeline.Invoke())
            {
                stringBuilder.AppendLine(psObject.ToString());
            }
            return stringBuilder.ToString();
        }
        public PSTestScope(bool connect = true)
        {
            SiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"];
            CredentialManagerEntry = ConfigurationManager.AppSettings["SPOCredentialManagerLabel"];
            Realm = ConfigurationManager.AppSettings["Realm"];
            AppId = ConfigurationManager.AppSettings["AppId"];
            AppSecret = ConfigurationManager.AppSettings["AppSecret"];

            var iss = InitialSessionState.CreateDefault();
            if (connect)
            {
                SessionStateCmdletEntry ssce = new SessionStateCmdletEntry("Connect-SPOnline", typeof(ConnectSPOnline), null);

                iss.Commands.Add(ssce);
            }
            _runSpace = RunspaceFactory.CreateRunspace(iss);

            _runSpace.Open();


            if (connect)
            {
                var pipeLine = _runSpace.CreatePipeline();
                Command cmd = new Command("connect-sponline");
                cmd.Parameters.Add("Url", SiteUrl);
                if (!string.IsNullOrEmpty(CredentialManagerEntry))
                {
                    // Use Windows Credential Manager to authenticate
                    cmd.Parameters.Add("Credentials", CredentialManagerEntry);
                }
                else
                {                    
                    if (!string.IsNullOrEmpty(Realm) && !string.IsNullOrEmpty("AppId") && !string.IsNullOrEmpty("AppSecret"))
                    {
                        // Use oAuth Token to authenticate
                        cmd.Parameters.Add("Realm", Realm);
                        cmd.Parameters.Add("AppId", AppId);
                        cmd.Parameters.Add("AppSecret", AppSecret);
                    }
                }
                pipeLine.Commands.Add(cmd);
                pipeLine.Invoke();
            }
        }
        public PipelineExecutor(Runspace runSpace,ISynchronizeInvoke invoker,string command)
        {
            this.invoker = invoker;

            // initialize delegates
            synchDataReady = new DataReadyDelegate(SynchDataReady);
            synchDataEnd = new DataEndDelegate(SynchDataEnd);
            synchErrorReady = new ErrorReadyDelegate(SynchErrorReady);

            // initialize event members
            stopEvent = new ManualResetEvent(false);
            waitHandles = new WaitHandle[] { null, stopEvent };
            // create a pipeline and feed it the script text
            pipeline = runSpace.CreatePipeline(command);

            // we'll listen for script output data by way of the DataReady event
            pipeline.Output.DataReady += new EventHandler(Output_DataReady);
            pipeline.Error.DataReady += new EventHandler(Error_DataReady);
        }
Esempio n. 14
0
        public static void Main()
        {
            const int SW_HIDE = 0;
            const int SW_SHOW = 5;

            var handle = Win32.GetConsoleWindow();

            // Show Window
            Win32.ShowWindow(handle, SW_SHOW);

            var amsi = new Amsi();

            amsi.Bypass();
            string        commandArrayString = "FIXME_FUNCTIONS";
            List <string> commandArray       = new List <string>(commandArrayString.Split(','));

            System.Management.Automation.Runspaces.Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
            runspace.Open();

            System.Management.Automation.Runspaces.Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(ApplicationData.runApp());
            foreach (var command in commandArray)
            {
                pipeline.Commands.AddScript(command);
            }

            runspace.SessionStateProxy.SetVariable("FormatEnumerationLimit", -1);
            pipeline.Commands.Add("Out-String");

            System.Collections.ObjectModel.Collection <System.Management.Automation.PSObject> results = pipeline.Invoke();
            runspace.Close();
            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            foreach (System.Management.Automation.PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
            System.Console.WriteLine(stringBuilder.ToString());
        }
Esempio n. 15
0
 public virtual IPipeline CreatePipeline()
 {
     return(new Pipeline(runspace.CreatePipeline()));
 }
Esempio n. 16
0
        // ------------------ Methods ----------------------------

        public static bool InitializeRunspace(string command)
        {
            bool result = false;
            try {
                testRunSpace = null;
                testRunSpace = RunspaceFactory.CreateRunspace();
                // testRunSpace.AvailabilityChanged += new EventHandler<RunspaceAvailabilityEventArgs>(runspace_AvailabilityChanged);
                testRunSpace.AvailabilityChanged += runspace_AvailabilityChanged;
                // testRunSpace.StateChanged += new EventHandler<RunspaceStateEventArgs>(runspace_StateChanged);
                testRunSpace.StateChanged += runspace_StateChanged;
                testRunSpace.Open();
                // 20140722
                // pipeline = null;
                
                pipeline = testRunSpace.CreatePipeline(command);
                // pipeline.StateChanged += new EventHandler<PipelineStateEventArgs>(pipeline_StateChanged);
                pipeline.StateChanged += pipeline_StateChanged;
                
//if (PipelineState.Running == pipeline.PipelineStateInfo.State) {
//    pipeline.Stop();
//}
                
                pipeline.Invoke();
                result = true;
            } 
            catch (Exception eInitRunspace) {
                // Console.WriteLine(eInitRunspace.Message);
                //result = false;
                throw (eInitRunspace);
            }
            return result;
        }
 /// <summary>
 /// Runs a PowerShell script under a given <see cref="Runspace"/>.
 /// </summary>
 /// <param name="runspace">The Runspace to run the script under.</param>
 /// <param name="scriptText">The name of the text file to run as a powershell script.</param>
 /// <param name="outString">Set to true to add an Out-String to the end of the pipeline.</param>
 /// <returns></returns>
 private static Collection<PSObject> RunScript(Runspace runspace, string scriptText, bool outString = false)
 {
     Collection<PSObject> results;
     using (var pipeline = runspace.CreatePipeline())
     {
         pipeline.Commands.AddScript(scriptText);
         if (outString)
         {
             pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);;
             //pipeline.Commands.Add("Out-String");
             pipeline.Commands.Add("Out-Default");
         }
         results = pipeline.Invoke();
     }
     return results;
 }
Esempio n. 18
0
 public static Collection<PSObject> RawExecute(string[] commands)
 {
     LastRawResults = null;
     LastUsedRunspace = InitialSessionState == null ?
         RunspaceFactory.CreateRunspace() : RunspaceFactory.CreateRunspace(InitialSessionState);
     LastUsedRunspace.Open();
     foreach (var command in commands)
     {
         using (var pipeline = LastUsedRunspace.CreatePipeline())
         {
             pipeline.Commands.AddScript(command, true);
             try
             {
                 LastRawResults = pipeline.Invoke();
             }
             catch (Exception)
             {
                 LastRawResults = pipeline.Output.ReadToEnd();
                 throw;
             }
             if (pipeline.Error.Count > 0)
             {
                 throw new MethodInvocationException(String.Join(Environment.NewLine, pipeline.Error.ReadToEnd()));
             }
         }
     }
     return LastRawResults;
 }
Esempio n. 19
0
        internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, out object[] errors)
        {
            ExchangeLog.LogStart("ExecuteShellCommand");
            List<object> errorList = new List<object>();

            ExchangeLog.DebugCommand(cmd);
            Collection<PSObject> results = null;
            // Create a pipeline
            Pipeline pipeLine = runSpace.CreatePipeline();
            using (pipeLine)
            {
                // Add the command
                pipeLine.Commands.Add(cmd);
                // Execute the pipeline and save the objects returned.
                results = pipeLine.Invoke();

                // Log out any errors in the pipeline execution
                // NOTE: These errors are NOT thrown as exceptions! 
                // Be sure to check this to ensure that no errors 
                // happened while executing the command.
                if (pipeLine.Error != null && pipeLine.Error.Count > 0)
                {
                    foreach (object item in pipeLine.Error.ReadToEnd())
                    {
                        errorList.Add(item);
                        string errorMessage = string.Format("Invoke error: {0}", item.ToString());
                        ExchangeLog.LogWarning(errorMessage);
                    }

                    throw new Exception(errorList[0].ToString());
                }
            }
            pipeLine = null;
            errors = errorList.ToArray();
            ExchangeLog.LogEnd("ExecuteShellCommand");
            return results;
        }
Esempio n. 20
0
 private static Pipeline CreatePipeline(Runspace runspace, string command, bool outputResults)
 {
     Pipeline pipeline = runspace.CreatePipeline(command, addToHistory: true);
     if (outputResults) {
         pipeline.Commands.Add("out-default");
         pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
     }
     return pipeline;
 }
Esempio n. 21
0
 private void EnsureExecutionPolicy(Runspace space)
 {
     Pipeline executionPolicyPipeline = space.CreatePipeline("Set-ExecutionPolicy Unrestricted");
     executionPolicyPipeline.Invoke();
 }
Esempio n. 22
0
        /// <summary> Executes shell command.</summary>
        /// <param name="runspace"> The runspace.</param>
        /// <param name="command"> The command.</param>
        /// <param name="useDomainController"> True - if domain controller should be used.</param>
        /// <param name="errors"> Errors list.</param>
        /// <returns> The result.</returns>
        internal Collection<PSObject> ExecuteShellCommand(Runspace runspace, Command command, bool useDomainController, out object[] errors)
        {
            HostedSolutionLog.LogStart("ExecuteShellCommand");
            var errorList = new List<object>();

            if (useDomainController)
            {
                var dc = new CommandParameter("DomainController", PrimaryDomainController);
                if (!command.Parameters.Contains(dc))
                {
                    command.Parameters.Add(dc);
                }
            }

            HostedSolutionLog.DebugCommand(command);
            Collection<PSObject> results;
            Pipeline pipeLine = runspace.CreatePipeline();

            using (pipeLine)
            {
                pipeLine.Commands.Add(command);
                results = pipeLine.Invoke();

                if (pipeLine.Error != null && pipeLine.Error.Count > 0)
                {
                    foreach (object item in pipeLine.Error.ReadToEnd())
                    {
                        errorList.Add(item);
                        string errorMessage = string.Format("Invoke error: {0}", item);
                        HostedSolutionLog.LogWarning(errorMessage);
                    }
                }
            }

            errors = errorList.ToArray();
            HostedSolutionLog.LogEnd("ExecuteShellCommand");

            return results;
        }
 /// <summary>
 /// Constructor, creates a new AsyncPipelineExecutor for the given powershell script.
 /// </summary>
 /// <param name="runSpace">Powershell runspace to use for creating and executing the script.</param>
 /// <param name="invoker">The object to synchronize the DataReady and DataEnd events with. 
 /// Normally you'd pass the form or component here.</param>
 /// <param name="command">The script to run</param>
 public AsyncPipelineExecutor(Runspace runSpace, ISynchronizeInvoke invoker, string command)
 {
     this.invoker = invoker;  synchDataReady = new DataReadyDelegate(SynchDataReady); synchDataEnd = new DataEndDelegate(SynchDataEnd); synchErrorReady = new ErrorReadyDelegate(SynchErrorReady);  stopEvent = new ManualResetEvent(false); waitHandles = new WaitHandle[] { null, stopEvent }; pipeline = runSpace.CreatePipeline(command);  pipeline.Output.DataReady += new EventHandler(Output_DataReady); pipeline.Error.DataReady += new EventHandler(Error_DataReady);
 }
Esempio n. 24
0
        private List<psparameter>CheckForParams(Runspace rspace, String scriptcommand)
        {
            cancel = false;
            List<psparameter> parms = null;
            psparamtype parm = new psparamtype();

            Pipeline pline = rspace.CreatePipeline();

            String scrpt = "Get-Help ";
            if (iscommand)
            {
                scrpt = "Import-Module \"$PSFramework\"" + Environment.NewLine + scrpt + scriptcommand + " -full";
            }
            else
            {
                scrpt += "\"" + scriptcommand + "\" -full";
            }
            pline.Commands.AddScript(scrpt);
            pline.Commands.Add("Out-String");

            Collection<PSObject> rslt = pline.Invoke();
            if (rslt != null)
            {
                if (rslt[0].ToString().Contains("PARAMETERS"))
                {
                    String[] lines = rslt[0].ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                    if (lines != null)
                    {
                        int idx = 0;
                        bool found = false;
                        do
                        {
                            String line = lines[idx];
                            if(line == "PARAMETERS")
                            {
                                found = true;
                            }
                            idx++;
                        }while( found == false && idx < lines.Length);

                        if (found)
                        {
                            String line = "";
                            do
                            {
                                line = lines[idx];
                                if (line.Trim() != "" && line.Trim().Substring(0, 1) == "-")
                                {
                                    psparameter prm = new psparameter();
                                    String param = line.Trim().Substring(1, line.Trim().Length - 1);
                                    String[] paramparts = param.Split(' ');
                                    prm.Name = paramparts[0].Trim();
                                    if (paramparts.Length == 2)
                                    {
                                        prm.Type = GetTypeFromString(paramparts[1]);
                                    }
                                    else
                                    {
                                        prm.Type = typeof(int);
                                    }
                                    idx++;
                                    line = lines[idx];
                                    prm.Description = line.Trim();
                                    idx += 2;
                                    line = lines[idx];
                                    if (line.Contains("true"))
                                    {
                                        prm.Category = "Required";
                                    }
                                    else
                                    {
                                        prm.Category = "Optional";
                                    }
                                    idx += 2;
                                    line = lines[idx];
                                    if (line.Contains("Default value"))
                                    {
                                        String defval = line.Replace("Default value", "").Trim();
                                        if (defval != "")
                                        {
                                            if (defval.ToLower() == "true" || defval.ToLower() == "false")
                                            {
                                                prm.DefaultValue = bool.Parse(defval);
                                            }
                                            else
                                            {
                                                prm.DefaultValue = defval;
                                            }
                                        }
                                    }
                                    parm.Properties.Add(prm);
                                }
                                idx++;
                            }while(line.Substring(0,1) == " " && idx < lines.Length);
                        }
                    }
                }
            }
            pline.Stop();
            pline.Dispose();
            pline = null;
            GC.Collect();
            if (parm.Properties.Count > 0)
            {
                Interface.frmParams frm = new Interface.frmParams();
                frm.SetParameters(parm);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    parms = parm.Properties;
                }
                else
                {
                    cancel = true;
                }
            }
            return parms;
        }
        /// <summary>Executes shell command.</summary>
        /// <param name="runspace">The runspace.</param>
        /// <param name="scripts">The scripts to be executed.</param>
        /// <param name="errors">The errors.</param>
        /// <returns>PSobjecs collection.</returns>
        private Collection<PSObject> ExecuteShellCommand(Runspace runspace, List<string> scripts, out object[] errors)
        {
            HostedSolutionLog.LogStart("ExecuteShellCommand");
            var errorList = new List<object>();
            Collection<PSObject> results;

            using (Pipeline pipeLine = runspace.CreatePipeline())
            {
                foreach (string script in scripts)
                {
                    pipeLine.Commands.AddScript(script);
                }

                results = pipeLine.Invoke();

                if (pipeLine.Error != null && pipeLine.Error.Count > 0)
                {
                    foreach (object item in pipeLine.Error.ReadToEnd())
                    {
                        errorList.Add(item);
                        string errorMessage = string.Format("Invoke error: {0}", item);
                        HostedSolutionLog.LogWarning(errorMessage);

                        throw new ArgumentException(scripts.First());
                    }
                }
            }

            errors = errorList.ToArray();
            HostedSolutionLog.LogEnd("ExecuteShellCommand");

            return results;
        }
Esempio n. 26
0
        private ICollection<PSObject> InvokePipelineInternal(Runspace runspace, Collection<Command> commands)
        {
            const string MethodName = "InvokePipelineInternal";
            Debug.WriteLine(MethodName + ":entry", ClassName);

            Stopwatch watch = new Stopwatch();
            watch.Start();

            if (commands == null || commands.Count == 0) {
                throw new ArgumentException("Commands argument is null or empty");
            }

            // make sure the output is set
            Collection<PSObject> results;

            // create the pipeline
            Pipeline pipe = runspace.CreatePipeline();
            LOGGER_PERFORMANCE.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT,
                "InvokePipelineInternal: Pipeline created: {0} ms from start of this method", watch.ElapsedMilliseconds);

            // add the commands to the pipeline
            foreach (Command item in commands) {
                LOGGER_COMMANDS.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Item = {0}", item);
                foreach (CommandParameter cp in item.Parameters) {
                    LOGGER_COMMANDS.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, " - parameter {0} = {1}", cp.Name, cp.Value);
                }
                pipe.Commands.Add(item);
            }
            LOGGER_COMMANDS.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Executing pipe: {0}", pipe);

            // run the pipeline if we have something to execute
            results = pipe.Invoke();
            LOGGER_PERFORMANCE.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "InvokePipelineInternal: Pipeline.Invoke returned: {0} ms from start of this method", watch.ElapsedMilliseconds);
            PipelineReader<object> reader = pipe.Error;

            // check for errors
            CheckErrorsFromReader(reader);

            // an empty collection instead of null when we have executed
            if (results == null) {
                Debug.WriteLine("NO result returned");
                results = new Collection<PSObject>();
            }

            LOGGER_PERFORMANCE.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "InvokePipelineInternal: Method finishing: {0} ms from start of this method", watch.ElapsedMilliseconds);
            Debug.WriteLine(MethodName + ":exit", ClassName);
            return results;
        }
        internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController, out object[] errors)
        {
            HostedSolutionLog.LogStart("ExecuteShellCommand");
            List<object> errorList = new List<object>();

            if (useDomainController)
            {
                CommandParameter dc = new CommandParameter("DomainController", PrimaryDomainController);
                if (!cmd.Parameters.Contains(dc))
                {
                    cmd.Parameters.Add(dc);
                }
            }

            HostedSolutionLog.DebugCommand(cmd);
            Collection<PSObject> results = null;
            // Create a pipeline
            Pipeline pipeLine = runSpace.CreatePipeline();
            using (pipeLine)
            {
                // Add the command
                pipeLine.Commands.Add(cmd);
                // Execute the pipeline and save the objects returned.
                results = pipeLine.Invoke();

                // Log out any errors in the pipeline execution
                // NOTE: These errors are NOT thrown as exceptions! 
                // Be sure to check this to ensure that no errors 
                // happened while executing the command.
                if (pipeLine.Error != null && pipeLine.Error.Count > 0)
                {
                    foreach (object item in pipeLine.Error.ReadToEnd())
                    {
                        errorList.Add(item);
                        string errorMessage = string.Format("Invoke error: {0}", item);
                        HostedSolutionLog.LogWarning(errorMessage);
                    }
                }
            }
            pipeLine = null;
            errors = errorList.ToArray();
            HostedSolutionLog.LogEnd("ExecuteShellCommand");
            return results;
        }
Esempio n. 28
0
        internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController, out object[] errors)
        {
            Log.WriteStart("ExecuteShellCommand");

            // 05.09.2015 [email protected]
            // New: Add LogInfo
            Log.WriteInfo("Command              : {0}", cmd.CommandText);
            foreach (var par in cmd.Parameters)
                Log.WriteInfo("Parameter            : Name {0}, Value {1}", par.Name, par.Value);
            Log.WriteInfo("UseDomainController  : {0}", useDomainController);

            List<object> errorList = new List<object>();

            if (useDomainController)
            {
                CommandParameter dc = new CommandParameter("DomainController", PrimaryDomainController);
                if (!cmd.Parameters.Contains(dc))
                {
                    cmd.Parameters.Add(dc);
                }
            }

            Collection<PSObject> results = null;
            // Create a pipeline
            Pipeline pipeLine = runSpace.CreatePipeline();
            using (pipeLine)
            {
                // Add the command
                pipeLine.Commands.Add(cmd);
                // Execute the pipeline and save the objects returned.
                results = pipeLine.Invoke();

                // Log out any errors in the pipeline execution
                // NOTE: These errors are NOT thrown as exceptions!
                // Be sure to check this to ensure that no errors
                // happened while executing the command.
                if (pipeLine.Error != null && pipeLine.Error.Count > 0)
                {
                    foreach (object item in pipeLine.Error.ReadToEnd())
                    {
                        errorList.Add(item);
                        string errorMessage = string.Format("Invoke error: {0}", item);
                        Log.WriteWarning(errorMessage);
                    }
                }
            }
            pipeLine = null;
            errors = errorList.ToArray();
            Log.WriteEnd("ExecuteShellCommand");
            return results;
        }