Exemplo n.º 1
0
        private static ScriptOutput Execute(string scriptBlock, IDictionary <string, object> parameters = null, string workingDirectory = null)
        {
            if (string.IsNullOrWhiteSpace(scriptBlock))
            {
                throw new ArgumentNullException(nameof(scriptBlock));
            }

            using (var shell = PowerShell.Create())
            {
                if (!string.IsNullOrEmpty(workingDirectory))
                {
                    shell.AddScript($"{Set_Location} \"{workingDirectory}\"");
                }

                var script = shell.AddScript(scriptBlock);

                if (parameters != null)
                {
                    script.AddParameters(parameters.ToDictionary(k => k.Key, v => v.Value));
                }

                var output = ScriptOutput.ExecuteAndOutput(script);
                if (shell.Streams.Error.Count > 0)
                {
                    throw new AggregateException(shell.Streams.Error.Select(e => e.Exception));
                }

                return(output);
            }
        }