コード例 #1
0
        public void SinglePSObjectOutput()
        {
            // Arrange
            var scriptContent = new StringBuilder();

            scriptContent.AppendLine("$psObject = New-Object PSObject");
            scriptContent.AppendLine("$psObject | Add-Member -MemberType NoteProperty -Name 'Foo' -Value 'TestFoo'");
            scriptContent.AppendLine("$psObject | Add-Member -MemberType NoteProperty -Name 'Bar' -Value 'TestBar'");
            scriptContent.AppendLine("$psObject");

            // Act
            IScriptExecutionResult result = null;
            var task = _scriptExecutionEngine.ExecuteScriptAsync(scriptContent.ToString(), OutputObjectsFormat.Json).
                       ContinueWith((executionResult) => {
                result = executionResult.Result;
            });

            task.Wait();

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(ScriptState.Success, result.State);
            Assert.IsNotEmpty(result.OutputObjectCollection.SerializedObjects);
            Assert.AreEqual(1, result.OutputObjectCollection.SerializedObjects.Length);
            var jsonObject = result.OutputObjectCollection.SerializedObjects[0];

            Assert.IsTrue(jsonObject.Contains(@"""TypeName"": ""System.Management.Automation.PSCustomObject"","));
            Assert.IsTrue(jsonObject.Contains(@"""Interfaces"": null,"));
            Assert.IsTrue(jsonObject.Contains(@"""Foo"": ""TestFoo"""));
            Assert.IsTrue(jsonObject.Contains(@"""Bar"": ""TestBar"""));
        }
コード例 #2
0
        public void StreamsAreCapturedBeforeScriptCancellation()
        {
            // Arrange
            var errorMessage  = "Test Error";
            var scriptContent = "while ($true) { Write-Error " + $"'{errorMessage}'" + "; Start-Sleep 1; }";

            // Act
            var cancellationToken = new CancellationTokenSource();

            IScriptExecutionResult result = null;
            var task = _scriptExecutionEngine.ExecuteScriptAsync(scriptContent, cancellationToken.Token).
                       ContinueWith((executionResult) => {
                result = executionResult.Result;
            });

            Thread.Sleep(TimeSpan.FromSeconds(2));
            cancellationToken.Cancel();
            task.Wait();

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(ScriptState.Canceled, result.State);
            Assert.IsNotEmpty(result.Streams.Error);
            Assert.AreEqual(errorMessage, result.Streams.Error[0].Message);
        }
コード例 #3
0
        public void ObjectWithDatePropertyOutput()
        {
            // Arrange
            var scriptContent = new StringBuilder();

            scriptContent.AppendLine("$dt = Get-Date -Day 3 -Month 3 -Year 2013 -Hour 12 -Minute 0 -Second 0 -Millisecond 0");
            scriptContent.AppendLine("$psObject = New-Object PSObject");
            scriptContent.AppendLine("$psObject | Add-Member -MemberType NoteProperty -Name 'Time' -Value $dt");
            scriptContent.AppendLine("$psObject");
            //    Expect ISO 8601 date format
            var expectedDateValue = new DateTime(2013, 3, 3, 12, 0, 0, DateTimeKind.Local).
                                    ToUniversalTime().
                                    GetDateTimeFormats('o')[0];

            // Act
            IScriptExecutionResult result = null;
            var task = _scriptExecutionEngine.ExecuteScriptAsync(scriptContent.ToString(), OutputObjectsFormat.Json).
                       ContinueWith((executionResult) => {
                result = executionResult.Result;
            });

            task.Wait();

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(ScriptState.Success, result.State);
            Assert.IsNotEmpty(result.OutputObjectCollection.SerializedObjects);
            Assert.AreEqual(1, result.OutputObjectCollection.SerializedObjects.Length);
            var jsonObject = result.OutputObjectCollection.SerializedObjects[0];

            Assert.IsTrue(jsonObject.Contains($"\"Time\": \"{expectedDateValue}\""));
        }
コード例 #4
0
        public void DateOutput()
        {
            // Arrange
            var scriptContent = "Get-Date -Day 3 -Month 3 -Year 2013 -Hour 12 -Minute 0 -Second 0 -Millisecond 0";
            //    Expect ISO 8601 date format
            var expectedDateValue = new DateTime(2013, 3, 3, 12, 0, 0, DateTimeKind.Local).
                                    ToUniversalTime().
                                    GetDateTimeFormats('o')[0];

            // Act
            IScriptExecutionResult result = null;
            var task = _scriptExecutionEngine.ExecuteScriptAsync(scriptContent, OutputObjectsFormat.Json).
                       ContinueWith((executionResult) => {
                result = executionResult.Result;
            });

            task.Wait();

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(ScriptState.Success, result.State);
            Assert.IsNotEmpty(result.OutputObjectCollection.SerializedObjects);
            Assert.AreEqual(1, result.OutputObjectCollection.SerializedObjects.Length);
            var jsonObject = result.OutputObjectCollection.SerializedObjects[0];

            Assert.IsTrue(jsonObject.Contains(@"""TypeName"": ""System.DateTime"","));
            Assert.IsTrue(jsonObject.Contains($"\"Value\": \"{expectedDateValue}\""));
        }
コード例 #5
0
        public void HashtableOutput()
        {
            // Arrange
            var scriptContent = new StringBuilder();

            scriptContent.AppendLine("$ht = @{}");
            scriptContent.AppendLine("$ht['Foo'] = 'TestFoo'");
            scriptContent.AppendLine("$ht['Bar'] = 'TestBar'");
            scriptContent.AppendLine("$ht");

            // Act
            IScriptExecutionResult result = null;
            var task = _scriptExecutionEngine.ExecuteScriptAsync(scriptContent.ToString(), OutputObjectsFormat.Json).
                       ContinueWith((executionResult) => {
                result = executionResult.Result;
            });

            task.Wait();

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(ScriptState.Success, result.State);
            Assert.IsNotEmpty(result.OutputObjectCollection.SerializedObjects);
            Assert.AreEqual(1, result.OutputObjectCollection.SerializedObjects.Length);
            var jsonObject = result.OutputObjectCollection.SerializedObjects[0];

            Assert.IsTrue(jsonObject.Contains(@"""TypeName"": ""System.Collections.Hashtable"","));
            Assert.IsTrue(jsonObject.Contains(@"""System.Collections.IDictionary"""));
            Assert.IsTrue(jsonObject.Contains(@"""Foo"": ""TestFoo"""));
            Assert.IsTrue(jsonObject.Contains(@"""Bar"": ""TestBar"""));
        }
コード例 #6
0
        public void Start(IRunspace runspaceClient, string scriptId, string scriptName, IScriptExecutionStoreProvider scriptExecutionWriter)
        {
            int maxGetLastScriptFailures = 3;
            int lastScriptFailures       = 0;

            // Initialize scriptExecutionWriter with running script execution with Id, Name, and State
            scriptExecutionWriter.WriteScriptExecution(new NamedScriptExecution {
                Name  = scriptName,
                Id    = scriptId,
                State = ScriptState.Running
            });

            Task.Run(() => {
                IScriptExecutionResult scriptExecutionResult = null;
                do
                {
                    try {
                        scriptExecutionResult = runspaceClient.GetScript(scriptId);
                    } catch (Exception exc) {
                        lastScriptFailures++;
                        _logger.Log(LogLevel.Error, exc.ToString());
                    }

                    scriptExecutionWriter.WriteScriptExecution(new NamedScriptExecution(scriptName, scriptExecutionResult));
                    scriptExecutionWriter.WriteScriptExecutionOutput(new ScriptExecutionOutput(scriptExecutionResult));
                    scriptExecutionWriter.WriteScriptExecutionDataStreams(new ScriptExecutionDataStreams(scriptExecutionResult?.Streams));

                    Thread.Sleep(500);
                } while (lastScriptFailures < maxGetLastScriptFailures && scriptExecutionResult.State == ScriptState.Running);

                if (lastScriptFailures >= maxGetLastScriptFailures)
                {
                    // Retrieval of last script failed which mean script has been lost because
                    // bad communication with the runspace
                    // 1. Read the last persisted result
                    // 2. Update Script ExecutionState to Error
                    // 3. Write script state
                    var lastPersistedScript    = scriptExecutionWriter.ReadScriptExecution();
                    var updatedScriptExecution = new NamedScriptExecution {
                        Name                = lastPersistedScript?.Name,
                        Id                  = lastPersistedScript?.Id,
                        StarTime            = lastPersistedScript?.StarTime,
                        EndTime             = DateTime.Now,
                        OutputObjectsFormat = lastPersistedScript?.OutputObjectsFormat ?? OutputObjectsFormat.Text,
                        State               = ScriptState.Error,
                        Reason              = APIGatewayResources.PollingScriptExecutionPersister_ScriptFailed_RunspaceDisappeared
                    };
                    scriptExecutionWriter.WriteScriptExecution(updatedScriptExecution);
                }

                scriptExecutionWriter.Flush();

                ScriptResultPersisted?.Invoke(this, new ScriptResultStoredEventArgs {
                    ScriptId = scriptId
                });
            });
        }
コード例 #7
0
 public ScriptResult(string scriptName, IScriptExecutionResult scriptResult)
 {
     Name   = string.IsNullOrEmpty(scriptName) ? scriptResult.Name : scriptName;
     Id     = scriptResult.Id;
     Reason = scriptResult.Reason;
     State  = scriptResult.State;
     OutputObjectsFormat = scriptResult.OutputObjectsFormat;
     StarTime            = scriptResult.StarTime;
     EndTime             = scriptResult.EndTime;
 }
コード例 #8
0
 public NamedScriptExecution(string scriptName, IScriptExecutionResult scriptResult)
 {
     Name = scriptName;
     if (scriptResult != null)
     {
         Id     = scriptResult.Id;
         Reason = scriptResult.Reason;
         State  = scriptResult.State;
         OutputObjectsFormat = scriptResult.OutputObjectsFormat;
         StarTime            = scriptResult.StarTime;
         EndTime             = scriptResult.EndTime;
     }
 }
コード例 #9
0
        public ScriptExecutionOutput(IScriptExecutionResult scriptExecutionResult)
        {
            switch (scriptExecutionResult?.OutputObjectsFormat)
            {
            case OutputObjectsFormat.Json:
                OutputObjects = scriptExecutionResult.OutputObjectCollection.SerializedObjects;
                break;

            case OutputObjectsFormat.Text:
                OutputObjects = new string[]
                { scriptExecutionResult.OutputObjectCollection.FormattedTextPresentation };
                break;

            default:
                break;
            }
        }
コード例 #10
0
        public void MultipleScriptExecution()
        {
            // Arrange
            var script2Content = "Get-ChildItem";

            // Act
            _scriptExecutionEngine.ExecuteScriptAsync(script2Content).Wait();

            IScriptExecutionResult result = null;
            var task = _scriptExecutionEngine.ExecuteScriptAsync(script2Content).
                       ContinueWith((executionResult) => {
                result = executionResult.Result;
            });

            task.Wait();

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(ScriptState.Success, result.State);
            Assert.IsNotEmpty(result.OutputObjectCollection.FormattedTextPresentation);
        }
コード例 #11
0
        public void CancelScriptExecution()
        {
            // Arrange
            var scriptContent = "while ($true) { Write-Output '23'; Start-Sleep 1; }";

            // Act
            var cancellationToken = new CancellationTokenSource();

            IScriptExecutionResult result = null;
            var task = _scriptExecutionEngine.ExecuteScriptAsync(scriptContent, cancellationToken.Token).
                       ContinueWith((executionResult) => {
                result = executionResult.Result;
            });

            cancellationToken.Cancel();
            task.Wait();

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(ScriptState.Canceled, result.State);
            Assert.IsTrue(result.Reason.Contains("The pipeline has been stopped"));
            Assert.NotNull(result.StarTime);
            Assert.NotNull(result.EndTime);
        }
コード例 #12
0
        public void DoubleOutput()
        {
            // Arrange
            var scriptContent = "[double]35.6";

            // Act
            IScriptExecutionResult result = null;
            var task = _scriptExecutionEngine.ExecuteScriptAsync(scriptContent, OutputObjectsFormat.Json).
                       ContinueWith((executionResult) => {
                result = executionResult.Result;
            });

            task.Wait();

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(ScriptState.Success, result.State);
            Assert.IsNotEmpty(result.OutputObjectCollection.SerializedObjects);
            Assert.AreEqual(1, result.OutputObjectCollection.SerializedObjects.Length);
            var jsonObject = result.OutputObjectCollection.SerializedObjects[0];

            Assert.IsTrue(jsonObject.Contains(@"""TypeName"": ""System.Double"","));
            Assert.IsTrue(jsonObject.Contains(@"""Value"": 35.6"));
        }