Ejemplo n.º 1
0
        /// <summary>
        /// Invokes the given command in the specified runspace.
        /// </summary>
        /// <param name="runspace">An instance of <see cref="Runspace"/> used to invoke the command.</param>
        /// <param name="commmand">An instance of <see cref="Command"/> representing the command to be invoked.</param>
        /// <param name="parameters">A collection of parameters to be included when invoking the command.</param>
        /// <returns>A collection of <see cref="PSObject"/>s that represent the output from the command.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="runspace"/> is null.
        /// or
        /// <paramref name="command"/> is null.
        /// or
        /// <paramref name="parameters"/> is null.
        /// </exception>
        public Collection <PSObject> InvokeCommand(Runspace runspace, Command command, CommandParameterCollection parameters)
        {
            Collection <PSObject> results;
            DateTime startTime;
            Dictionary <string, double> eventMetrics;
            Dictionary <string, string> eventProperties;

            command.AssertNotNull(nameof(command));
            parameters.AssertNotNull(nameof(parameters));
            runspace.AssertNotNull(nameof(runspace));

            try
            {
                startTime = DateTime.Now;

                runspace.Open();

                using (Pipeline pipeline = runspace.CreatePipeline())
                {
                    foreach (CommandParameter parameter in parameters)
                    {
                        command.Parameters.Add(parameter);
                    }

                    pipeline.Commands.Add(command);
                    results = pipeline.Invoke();

                    // Ensure that no errors were encountered with the script execution.
                    ValidatePipeline(pipeline);
                }

                // Capture the request for the customer summary for analysis.
                eventProperties = new Dictionary <string, string>
                {
                    { "CommandText", command.CommandText }
                };

                // Track the event measurements for analysis.
                eventMetrics = new Dictionary <string, double>
                {
                    { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds }
                };

                service.Telemetry.TrackEvent("InvokeCommand", eventProperties, eventMetrics);

                return(results);
            }
            finally
            {
                eventMetrics    = null;
                eventProperties = null;
            }
        }