Ejemplo n.º 1
0
 public static bool TryParse(TextReader scriptText, out PowerShellScriptInfo info)
 {
     try
     {
         info = Parse(scriptText);
         return(true);
     }
     catch
     {
         info = null;
         return(false);
     }
 }
Ejemplo n.º 2
0
        public static async Task <ExecutePowerShellJob.Result> ExecuteScriptAsync(ILogSink logger, IOperationExecutionContext context, string fullScriptName, IReadOnlyDictionary <string, RuntimeValue> arguments, IDictionary <string, RuntimeValue> outArguments, bool collectOutput, EventHandler <PSProgressEventArgs> progressUpdateHandler)
        {
            var scriptText = await GetScriptTextAsync(logger, fullScriptName, context);

            var variables  = new Dictionary <string, RuntimeValue>();
            var parameters = new Dictionary <string, RuntimeValue>();

            if (PowerShellScriptInfo.TryParse(new StringReader(scriptText), out var scriptInfo))
            {
                foreach (var var in arguments)
                {
                    var value = var.Value;
                    var param = scriptInfo.Parameters.FirstOrDefault(p => string.Equals(p.Name, var.Key, StringComparison.OrdinalIgnoreCase));
                    if (param != null && param.IsBooleanOrSwitch)
                    {
                        value = value.AsBoolean() ?? false;
                    }
                    if (param != null)
                    {
                        parameters[param.Name] = value;
                    }
                    else
                    {
                        variables[var.Key] = value;
                    }
                }
            }
            else
            {
                variables = arguments.ToDictionary(a => a.Key, a => a.Value);
            }

            var jobRunner = context.Agent.GetService <IRemoteJobExecuter>();

            var job = new ExecutePowerShellJob
            {
                ScriptText     = scriptText,
                DebugLogging   = false,
                VerboseLogging = true,
                CollectOutput  = collectOutput,
                LogOutput      = !collectOutput,
                Variables      = variables,
                Parameters     = parameters,
                OutVariables   = outArguments.Keys.ToArray()
            };

            job.MessageLogged += (s, e) => logger.Log(e.Level, e.Message);
            if (progressUpdateHandler != null)
            {
                job.ProgressUpdate += progressUpdateHandler;
            }

            var result = (ExecutePowerShellJob.Result) await jobRunner.ExecuteJobAsync(job, context.CancellationToken);

            if (result.ExitCode != null)
            {
                logger.LogDebug("Script exit code: " + result.ExitCode);
            }

            foreach (var var in result.OutVariables)
            {
                outArguments[var.Key] = var.Value;
            }

            return(result);
        }