Пример #1
0
        public override RuntimeValue Evaluate(IVariableFunctionContext context)
        {
            if (!(context is IOperationExecutionContext execContext))
            {
                throw new NotSupportedException("This function can currently only be used within an execution.");
            }

            var job = new ExecutePowerShellJob
            {
                CollectOutput = true,
                ScriptText    = this.ScriptText,
                Variables     = PowerShellScriptRunner.ExtractVariables(this.ScriptText, execContext)
            };

            var jobExecuter = execContext.Agent.GetService <IRemoteJobExecuter>();
            var result      = (ExecutePowerShellJob.Result)jobExecuter.ExecuteJobAsync(job, execContext.CancellationToken).GetAwaiter().GetResult();

            if (result.Output.Count == 1)
            {
                return(result.Output[0]);
            }
            else
            {
                return(new RuntimeValue(result.Output));
            }
        }
Пример #2
0
        public override async Task ExecuteAsync(IOperationExecutionContext context)
        {
            if (context.Simulation && !this.RunOnSimulation)
            {
                this.LogInformation("Executing PowerShell script...");
                return;
            }

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

            var job = new ExecutePowerShellJob
            {
                ScriptText       = this.ScriptText,
                DebugLogging     = this.DebugLogging,
                VerboseLogging   = this.VerboseLogging,
                CollectOutput    = false,
                LogOutput        = true,
                Variables        = PowerShellScriptRunner.ExtractVariables(this.ScriptText, context),
                Isolated         = this.Isolated,
                WorkingDirectory = context.WorkingDirectory
            };

            job.MessageLogged += (s, e) => this.Log(e.Level, e.Message);

            job.ProgressUpdate += (s, e) => Interlocked.Exchange(ref this.currentProgress, e);

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

            PSUtil.LogExit(this, result.ExitCode, this.SuccessExitCode);
        }
Пример #3
0
        private void BtnRunScript_Click(object sender, EventArgs e)
        {
            PowerShellScriptRunner scriptRunner = new PowerShellScriptRunner("TestScript.ps1");

            scriptRunner.RunScript();
            //Get Powershell running with new assembly nuget pack
            //using (PowerShell shell = PowerShell.Create())
            //{
            //    string fileName = "TestScript.ps1";
            //    string path = Path.Combine(Environment.CurrentDirectory, @"Scripts\", fileName);

            //    //shell.AddCommand("Get-Content " + path + " | Invoke-Expression");
            //    shell.AddCommand("Get-Content").AddArgument(path);
            //    shell.AddCommand("Invoke-Expression");
            //    shell.Invoke();

            //    Console.WriteLine("TEST");
            //    // use "AddParameter" to add a single parameter to the last command/script on the pipeline.
            //    //shell.AddParameter("param1", "parameter 1 value!");

            //}

            //Execute a powershell script
            //string finalPath = "Get-Content " + path + " | Invoke-Expression";
            //System.Diagnostics.Process.Start("PowerShell.exe", finalPath);
        }
        public override async Task <PersistedConfiguration> CollectAsync(IOperationCollectionContext context)
        {
            if (!this.ValidateConfiguration())
            {
                return(null);
            }

            ExecutePowerShellJob.Result result;

            if (!string.IsNullOrWhiteSpace(this.CollectScriptAsset))
            {
                result = await PSUtil.ExecuteScriptAsync(
                    logger : this,
                    context : context,
                    fullScriptName : this.CollectScriptAsset,
                    arguments : this.CollectScriptParams ?? new Dictionary <string, RuntimeValue>(),
                    outArguments : new Dictionary <string, RuntimeValue>(),
                    collectOutput : !this.UseExitCode,
                    progressUpdateHandler : (s, e) => Interlocked.Exchange(ref this.currentProgress, e)
                    );
            }
            else
            {
                var jobRunner = context.Agent.GetService <IRemoteJobExecuter>();

                var job = new ExecutePowerShellJob
                {
                    ScriptText     = this.CollectScript,
                    DebugLogging   = this.DebugLogging,
                    VerboseLogging = this.VerboseLogging,
                    CollectOutput  = !this.UseExitCode,
                    LogOutput      = this.UseExitCode,
                    Variables      = PowerShellScriptRunner.ExtractVariables(this.CollectScript, context)
                };

                job.MessageLogged  += (s, e) => this.Log(e.Level, e.Message);
                job.ProgressUpdate += (s, e) => Interlocked.Exchange(ref this.currentProgress, e);

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

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

            return(new KeyValueConfiguration
            {
                Key = this.ConfigurationKey,
                Value = this.UseExitCode ? result.ExitCode?.ToString() : string.Join(", ", result.Output)
            });
        }
        public override IActiveScript ExecuteScript(ScriptExecutionContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            var ps = new PowerShellScriptRunner();
            try
            {
                string fullText;

                using (var reader = GetTextReader2(context))
                {
                    fullText = reader.ReadToEnd();
                }

                ps.PowerShell.AddScript(fullText);

                Collection<PSParseError> errors;
                var tokens = PSParser.Tokenize(fullText, out errors);

                int paramIndex = tokens
                    .TakeWhile(t => t.Type != PSTokenType.Keyword || !string.Equals(t.Content, "param", StringComparison.OrdinalIgnoreCase))
                    .Count();

                var parameters = context
                    .Arguments
                    .GroupJoin(
                        this.ScrapeParameters(tokens.Skip(paramIndex + 1)),
                        a => a.Key,
                        p => p.Name,
                        (a, p) => new { Name = a.Key, a.Value, Metadata = p.FirstOrDefault() },
                        StringComparer.OrdinalIgnoreCase);

                foreach (var arg in parameters)
                {
                    if (arg.Metadata != null)
                    {
                        if (arg.Metadata.DefaultValue == null || !string.IsNullOrEmpty(arg.Value))
                        {
                            if (string.Equals(arg.Metadata.Type, "switch", StringComparison.OrdinalIgnoreCase))
                            {
                                if (string.Equals(arg.Value, this.TrueValue, StringComparison.OrdinalIgnoreCase))
                                    ps.PowerShell.AddParameter(arg.Name);
                            }
                            else if (string.Equals(arg.Metadata.Type, "bool", StringComparison.OrdinalIgnoreCase) || string.Equals(arg.Metadata.Type, "System.Boolean", StringComparison.OrdinalIgnoreCase))
                            {
                                ps.PowerShell.AddParameter(arg.Name, string.Equals(arg.Value, this.TrueValue, StringComparison.OrdinalIgnoreCase));
                            }
                            else
                            {
                                ps.PowerShell.AddParameter(arg.Name, arg.Value);
                            }
                        }
                    }
                    else
                    {
                        ps.PowerShell.AddParameter(arg.Name, arg.Value);
                    }
                }

                foreach (var var in context.Variables)
                    ps.PowerShell.Runspace.SessionStateProxy.SetVariable(var.Key, var.Value);

                return ps;
            }
            catch
            {
                ps?.Dispose();
                throw;
            }
        }