public void GetScript()
        {
            Script script1 = _scriptService.GetScript("5a768553-052e-47ee-bf48-68f8aaf9cd05");

            Assert.IsNotNull(script1);
            Assert.AreEqual(1, script1.ID);
            Assert.AreEqual("Test Script 1", script1.Name);

            Script script99 = _scriptService.GetScript("99");

            Assert.IsNull(script99);
        }
Exemplo n.º 2
0
        // GET get task parameters
        public String[] Get(String id)
        {
            Script script = _scriptService.GetScript(id);

            if (script != null)
            {
                IGhostRunnerScript ghostRunnerScript = ScriptHelper.GetGhostRunnerScript(script);

                if (ghostRunnerScript.HasParameters())
                {
                    return(ghostRunnerScript.GetAllParameters());
                }
                else
                {
                    return(new String[0]);
                }
            }
            else
            {
                return(new String[0]);
            }
        }
Exemplo n.º 3
0
        public ActionResult GetEditScriptDialog(String scriptId)
        {
            EditScriptModel editScriptModel = new EditScriptModel();

            editScriptModel.GhostRunnerScript = ScriptHelper.GetGhostRunnerScript(_scriptService.GetScript(scriptId));
            editScriptModel.User    = ((User)ViewData["User"]);
            editScriptModel.Project = editScriptModel.GhostRunnerScript.Project;

            return(PartialView("Partials/EditScript", editScriptModel));
        }
Exemplo n.º 4
0
        public ActionResult GetSequenceScriptParameters(String sequenceId, String scriptId)
        {
            SequenceScriptParametersModel sequenceScriptParametersModel = new SequenceScriptParametersModel();

            sequenceScriptParametersModel.Sequence = _sequenceService.GetSequence(sequenceId);
            sequenceScriptParametersModel.Script   = ScriptHelper.GetGhostRunnerScript(_scriptService.GetScript(scriptId));

            sequenceScriptParametersModel.TaskParameters = new List <TaskScriptParameter>();

            foreach (String parameter in sequenceScriptParametersModel.Script.GetAllParameters())
            {
                TaskScriptParameter taskParameter = new TaskScriptParameter();
                taskParameter.Name  = parameter;
                taskParameter.Value = String.Empty;

                sequenceScriptParametersModel.TaskParameters.Add(taskParameter);
            }

            return(PartialView("Partials/SequenceScriptParameters", sequenceScriptParametersModel));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Runs a PowerShell script with parameters and prints the resulting pipeline objects to the console output.
        /// </summary>
        /// <param name="scriptId">The script file contents.</param>
        /// <param name="scriptParameters">A dictionary of parameter names and parameter values.</param>
        /// <param name="outputHandler">The outputHandler to send the script output to.</param>
        private async Task StreamPowerShell(string scriptId, Dictionary <string, object> scriptParameters, Action <object> outputHandler)
        {
            string cacheKey = $"{Context.ConnectionId}|CancellationTokenSource";

            try
            {
                var script = ScriptService.GetScript(scriptId);

                outputHandler(new OutputRecord(OutputLevelName.System, "Loading script..."));
                Logger.Log(LogLevel.Information, $"{Context.User.Identity.Name} attempting to run {script.Name}");

                string scriptContents = script.GetContents();

                // Setup a custom runspace pool if configured on the script
                if (script.Runspace != null)
                {
                    InitializeRunspaces(script.Runspace);
                }

                // create a new hosted PowerShell instance potentially with a custom runspace.
                // wrap in a using statement to ensure resources are cleaned up.
                using (PowerShell ps = PowerShell.Create())
                {
                    // use the runspace pool, if it was created.
                    if (RsPool != null)
                    {
                        ps.RunspacePool = RsPool;
                    }

                    // specify the script code to run.
                    ps.AddScript(scriptContents);

                    // specify the parameters to pass into the script.
                    ps.AddParameters(scriptParameters);

                    // Subscribe to events from output
                    var output = new PSDataCollection <PSObject>();
                    output.DataAdded += (object sender, DataAddedEventArgs e) => WriteOutput <PSObject>(sender, e, outputHandler);

                    // subscribe to events from some of the streams

                    /// Handles data-added events for the error stream.
                    /// Note: Uncaught terminating errors will stop the pipeline completely.
                    /// Non-terminating errors will be written to this stream and execution will continue.
                    ps.Streams.Error.DataAdded   += (object sender, DataAddedEventArgs e) => WriteOutput <ErrorRecord>(sender, e, outputHandler);
                    ps.Streams.Warning.DataAdded += (object sender, DataAddedEventArgs e) => WriteOutput <WarningRecord>(sender, e, outputHandler);
                    /// Handles data-added events for the information stream.
                    /// Note: Write-Host and Write-Information messages will end up in the information stream.
                    ps.Streams.Information.DataAdded += (object sender, DataAddedEventArgs e) => WriteOutput <InformationRecord>(sender, e, outputHandler);
                    ps.Streams.Progress.DataAdded    += (object sender, DataAddedEventArgs e) => WriteOutput <ProgressRecord>(sender, e, outputHandler);
                    ps.Streams.Verbose.DataAdded     += (object sender, DataAddedEventArgs e) => WriteOutput <VerboseRecord>(sender, e, outputHandler);
                    ps.Streams.Debug.DataAdded       += (object sender, DataAddedEventArgs e) => WriteOutput <DebugRecord>(sender, e, outputHandler);

                    outputHandler(new OutputRecord(OutputLevelName.System, "Beginning script execution..."));

                    // setup our cancellation token for possible use later to cancel
                    CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                    // We basically want to cache the cancellationTokenSource until the script finishes (or is canceled)
                    var cacheExpiryOptions = new MemoryCacheEntryOptions
                    {
                        AbsoluteExpiration = DateTime.Now.AddDays(1),
                        Priority           = CacheItemPriority.High
                    };
                    MemoryCache.Set(cacheKey, cancellationTokenSource, cacheExpiryOptions);

                    // NOTE: the 'await' call is gone here so we can access the task object.
                    Task <PSDataCollection <PSObject> > asyncTask = ps.InvokeAsync();
                    asyncTask.Wait(cancellationTokenSource.Token); // Wait on the task until natural completion OR cancel token fires.
                    output = asyncTask.Result;                     // this object should contain the original PSObject results (pipeline output).
                }
            }
            catch (Exception ex)
            {
                Logger.Log(LogLevel.Error, ex, ex.Message);
                outputHandler(new OutputRecord(OutputLevelName.Error, ex.Message));
            }
            finally
            {
                outputHandler(new OutputRecord(OutputLevelName.System, "Script execution ended."));
                MemoryCache.Remove(cacheKey);
            }
        }