示例#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);
        }
        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)
            });
        }
示例#4
0
        private static ExecutePowerShellJob CreateJob(string method, Dictionary <string, RuntimeValueType> propertyTypes, DscConfiguration template)
        {
            var job = new ExecutePowerShellJob
            {
                CollectOutput = true,
                ScriptText    = $"Invoke-DscResource -Name $Name -Method {method} -Property $Property -ModuleName $ModuleName",
                Variables     = new Dictionary <string, RuntimeValue>(StringComparer.OrdinalIgnoreCase)
                {
                    ["Name"]       = template.ResourceName,
                    ["Property"]   = new RuntimeValue(template.ToPowerShellDictionary(propertyTypes)),
                    ["ModuleName"] = AH.CoalesceString(template.ModuleName, "PSDesiredStateConfiguration")
                }
            };

            return(job);
        }
示例#5
0
        protected async override Task <IEnumerable <PackageConfiguration> > CollectPackagesAsync(IOperationCollectionContext context)
        {
            var jobRunner = await context.Agent.GetServiceAsync <IRemoteJobExecuter>();

            var scriptText = "$results = Get-Module -ListAvailable";

            var job = new ExecutePowerShellJob
            {
                CollectOutput = true,
                OutVariables  = new[] { "results" },
                ScriptText    = scriptText
            };

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

            var modules = (result.OutVariables["results"].AsEnumerable() ?? result.OutVariables["results"].ParseDictionary() ?? Enumerable.Empty <RuntimeValue>())
                          .Select(parseModule).Where(m => m != null);

            return(modules);
示例#6
0
        private static async Task <Dictionary <string, RuntimeValueType> > GetPropertyTypesAsync(IOperationExecutionContext context, IRemoteJobExecuter jobRunner, string resourceName, string moduleName, ILogSink log)
        {
            var job = new ExecutePowerShellJob
            {
                CollectOutput = true,
                ScriptText    = @"$h = @{}
foreach($p in (Get-DscResource -Name $Name -Module $ModuleName).Properties) {
    $h[$p.Name] = $p.PropertyType
}
Write-Output $h",
                Variables     = new Dictionary <string, RuntimeValue>(StringComparer.OrdinalIgnoreCase)
                {
                    ["Name"]       = resourceName,
                    ["ModuleName"] = AH.CoalesceString(moduleName, "PSDesiredStateConfiguration")
                }
            };

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

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

            var properties = result.Output.FirstOrDefault().AsDictionary();

            var types = new Dictionary <string, RuntimeValueType>(StringComparer.OrdinalIgnoreCase);

            if (properties != null)
            {
                foreach (var p in properties)
                {
                    var value = p.Value.AsString();
                    types[p.Key] = (!string.IsNullOrWhiteSpace(value) && IsArrayPropertyRegex.IsMatch(value)) ? RuntimeValueType.Vector : RuntimeValueType.Scalar;
                }
            }

            return(types);
        }