internal PowerShellTask(string script)
 {
     this.pipeline = RunspaceFactory.CreateRunspace().CreatePipeline();
     this.pipeline.Commands.AddScript(script);
     this.pipeline.Runspace.Open();
     this.pipeline.Runspace.SessionStateProxy.SetVariable("log", this.Log);
 }
Esempio n. 2
0
        public IEnumerable<String> ProcessRecord(PSObject record)
        {
            if (record == null)
            {
                yield break;
            }

            if (_raw)
            {
                yield return record.ToString();
            }
            else
            {
                if (_pipeline == null)
                {
                    _pipeline = CreatePipeline();
                    _pipeline.InvokeAsync();
                }

                _pipeline.Input.Write(record);

                foreach (PSObject result in _pipeline.Output.NonBlockingRead())
                {
                    yield return result.ToString();
                }
            }
        }
 internal ExecutionCmdletHelperComputerName(System.Management.Automation.RemoteRunspace remoteRunspace, Pipeline pipeline, bool invokeAndDisconnect = false)
 {
     this.invokeAndDisconnect = invokeAndDisconnect;
     this.remoteRunspace = remoteRunspace;
     remoteRunspace.StateChanged += new EventHandler<RunspaceStateEventArgs>(this.HandleRunspaceStateChanged);
     base.pipeline = pipeline;
     pipeline.StateChanged += new EventHandler<PipelineStateEventArgs>(this.HandlePipelineStateChanged);
 }
Esempio n. 4
0
        public PipelineExecutor(Runspace runSpace, string command)
        {
            this.pipeline = runSpace.CreatePipeline(command);
            this.pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);

            this.pipeline.Output.DataReady += this.OutputDataReady;
            this.pipeline.Error.DataReady += this.ErrorDataReady;
        }
Esempio n. 5
0
 /// <summary>
 /// Initializes a new instance of pipeline wrapper wrapping the
 /// specified pipeline.
 /// </summary>
 /// <param name="pipeline">
 /// The pipeline to wrap.
 /// </param>
 public PipelineWrapper(Pipeline pipeline)
 {
     if (pipeline == null)
     {
         throw new ArgumentNullException("pipeline");
     }
     _pipeline = pipeline;
 }
Esempio n. 6
0
 public void Run(String command)
 {
     log.Info("Running command: " + command);
     _PipeLine = _RunSpace.CreatePipeline(command);
     _PipeLine.Input.Close();
     _OutPut = _PipeLine.Output;
     _OutPut.DataReady += _Output_DataReady;
     _PipeLine.InvokeAsync();
 }
 public void Run(String command)
 {
     this.Log().Info("Running command: {0}", command);
     _pipeLine = _runSpace.CreatePipeline(command);
     _pipeLine.Input.Close();
     _outPut = _pipeLine.Output;
     _outPut.DataReady += OutputDataReady;
     _pipeLine.InvokeAsync();
 }
        // void ContinueCommand(RemoteRunspace remoteRunspace, Pipeline cmd, PSHost host, bool inDebugMode, ExecutionContext context)
        public static void ContinueCommand(Runspace remoteRunspace, Pipeline cmd, PSHost host, bool inDebugMode,
            Runspace oldRunspace)
        {
            var remoteRunspaceType = typeof(EnterPSSessionCommand).Assembly.GetType("System.Management.Automation.RemoteRunspace");
            var executionContextType = typeof(EnterPSSessionCommand).Assembly.GetType("System.Management.Automation.ExecutionContext");
            var executionContext = typeof (Runspace).GetProperty("ExecutionContext", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(true).Invoke(remoteRunspace, new object[]{});
            var method = typeof(EnterPSSessionCommand).GetMethod("ContinueCommand",
                BindingFlags.NonPublic | BindingFlags.Static, null, new[] { remoteRunspaceType, typeof(Pipeline), typeof(PSHost), typeof(bool), executionContextType }, null);

            method.Invoke(null, new[] { remoteRunspace, cmd, host, inDebugMode, executionContext});
        }
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (this.pipeline.Runspace != null)
         {
             this.pipeline.Runspace.Dispose();
             this.pipeline = null;
         }
     }
 }
Esempio n. 10
0
        internal void PushPipeline(Pipeline pipeline)
        {
            // TODO: make sure that the "CurrentPipeline" is in the stack

            _pipelineStack.Push(pipeline);

            // TODO: create a new pipeline and replace the current one with it
            if (pipeline is LocalPipeline)
            {
                ((LocalPipeline)pipeline).RerouteExecutionContext(this);
            }

        }
Esempio n. 11
0
        public void Dispose()
        {
            if (_pipeline != null)
            {
                _pipeline.Dispose();
                _pipeline = null;
            }

            if (_runspace != null)
            {
                _runspace.Dispose();
                _runspace = null;
            }
        }
Esempio n. 12
0
        public IEnumerable<String> EndProcessing()
        {
            if (_runspace == null || _pipeline == null)
            {
                yield break;
            }

            _pipeline.Input.Close();

            foreach (PSObject obj in _pipeline.Output.ReadToEnd())
            {
                yield return obj.ToString();
            }

            _pipeline.Dispose();
            _pipeline = null;
        }
        public PipelineExecutor(Runspace runSpace,ISynchronizeInvoke invoker,string command)
        {
            this.invoker = invoker;

            // initialize delegates
            synchDataReady = new DataReadyDelegate(SynchDataReady);
            synchDataEnd = new DataEndDelegate(SynchDataEnd);
            synchErrorReady = new ErrorReadyDelegate(SynchErrorReady);

            // initialize event members
            stopEvent = new ManualResetEvent(false);
            waitHandles = new WaitHandle[] { null, stopEvent };
            // create a pipeline and feed it the script text
            pipeline = runSpace.CreatePipeline(command);

            // we'll listen for script output data by way of the DataReady event
            pipeline.Output.DataReady += new EventHandler(Output_DataReady);
            pipeline.Error.DataReady += new EventHandler(Error_DataReady);
        }
Esempio n. 14
0
        public static void Main()
        {
            const int SW_HIDE = 0;
            const int SW_SHOW = 5;

            var handle = Win32.GetConsoleWindow();

            // Show Window
            Win32.ShowWindow(handle, SW_SHOW);

            var amsi = new Amsi();

            amsi.Bypass();
            string        commandArrayString = "FIXME_FUNCTIONS";
            List <string> commandArray       = new List <string>(commandArrayString.Split(','));

            System.Management.Automation.Runspaces.Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
            runspace.Open();

            System.Management.Automation.Runspaces.Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(ApplicationData.runApp());
            foreach (var command in commandArray)
            {
                pipeline.Commands.AddScript(command);
            }

            runspace.SessionStateProxy.SetVariable("FormatEnumerationLimit", -1);
            pipeline.Commands.Add("Out-String");

            System.Collections.ObjectModel.Collection <System.Management.Automation.PSObject> results = pipeline.Invoke();
            runspace.Close();
            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            foreach (System.Management.Automation.PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
            System.Console.WriteLine(stringBuilder.ToString());
        }
Esempio n. 15
0
 public string Execute(RunnerArgs args)
 {
     _pipeline = Runspace.CreatePipeline();
     _pipeline.Commands.AddScript(args.Script);
     _pipeline.Commands.Add("Out-String");
     Collection<PSObject> psObjects;
     try
     {
         psObjects = _pipeline.Invoke();
     } catch(Exception e)
     {
         return e.Message;
     }
     if(_pipeline.Error.Count > 0)
     {
         var firstOrDefault = _pipeline.Error.ReadToEnd().FirstOrDefault();
         if (firstOrDefault != null)
         {
             return firstOrDefault.ToString();
         }
     }
     if(_pipeline.Output.Count > 0)
     {
         var firstOrDefault = _pipeline.Output.ReadToEnd().FirstOrDefault();
         if (firstOrDefault != null)
         {
             return firstOrDefault.ToString();
         }
     }
     var sb = new StringBuilder();
     foreach (var psObject in psObjects)
     {
         sb.AppendLine(psObject.ToString());
     }
     return sb.ToString();
 }
Esempio n. 16
0
 private void ConfigureConDepNodeModule(Pipeline pipeline, RemoteScriptFolders folders, PowerShellModulesToLoad modules)
 {
     if (modules.LoadConDepNodeModule)
     {
         var conDepNodeModule = string.Format(@"Import-Module {0}", folders.NodeScriptFolder);
         Logger.Verbose(conDepNodeModule);
         pipeline.Commands.AddScript(conDepNodeModule);
     }
 }
 internal PipelineAbstraction(Pipeline pipeline, Runspace runspace) : base(runspace)
 {
     this.Pipeline = pipeline;
 }
Esempio n. 18
0
 private static void ConfigureCommand(string commandOrScript, IEnumerable<CommandParameter> parameters, Pipeline pipeline)
 {
     if (parameters != null)
     {
         var cmd = new Command(commandOrScript, true);
         foreach (var param in parameters)
         {
             cmd.Parameters.Add(param);
         }
         pipeline.Commands.Add(cmd);
     }
     else
     {
         pipeline.Commands.AddScript(commandOrScript);
     }
     Logger.Verbose(commandOrScript);
 }
Esempio n. 19
0
 private void ConfigureConDepDotNetLibrary(Pipeline pipeline, RemoteScriptFolders folders, PowerShellModulesToLoad modules)
 {
     if (modules.LoadConDepDotNetLibrary)
     {
         var netLibraryCmd = string.Format(@"Add-Type -Path ""{0}""",
             Path.Combine(folders.PSTempFolder, "ConDep.Dsl.Remote.Helpers.dll"));
         Logger.Verbose(netLibraryCmd);
         pipeline.Commands.AddScript(netLibraryCmd);
     }
 }
Esempio n. 20
0
 /// <summary>
 /// Internal constructor
 /// </summary>
 /// <param name="pipeline">pipeline object associated with this operation</param>
 internal ExecutionCmdletHelperRunspace(Pipeline pipeline)
 {
     this.pipeline = pipeline;
     PipelineRunspace = pipeline.Runspace;
     this.pipeline.StateChanged += new EventHandler<PipelineStateEventArgs>(HandlePipelineStateChanged);
 }
Esempio n. 21
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="remoteRunspace">RemoteRunspace that is associated
        /// with this operation</param>
        /// <param name="pipeline">pipeline created from the remote runspace</param>
        /// <param name="invokeAndDisconnect">Indicates if pipeline should be disconnected after invoking command.</param>
        internal ExecutionCmdletHelperComputerName(RemoteRunspace remoteRunspace, Pipeline pipeline, bool invokeAndDisconnect = false)
        {
            Dbg.Assert(remoteRunspace != null,
                    "RemoteRunspace reference cannot be null");
            PipelineRunspace = remoteRunspace;

            _invokeAndDisconnect = invokeAndDisconnect;

            RemoteRunspace = remoteRunspace;
            remoteRunspace.StateChanged +=
                new EventHandler<RunspaceStateEventArgs>(HandleRunspaceStateChanged);

            Dbg.Assert(pipeline != null,
                    "Pipeline cannot be null or empty");

            this.pipeline = pipeline;
            pipeline.StateChanged +=
                new EventHandler<PipelineStateEventArgs>(HandlePipelineStateChanged);
        } // IREHelperComputerName
Esempio n. 22
0
        public static bool CloseRunspace()
        {
            bool result = false;
            try {
                try {
                    pipeline.Stop();
                }
                catch (Exception) {
                    // Console.WriteLine(eClosingPipeline.Message);
                }
                
                testRunSpace.Close();
                
                testRunSpace.Dispose();
                
                testRunSpace = null;
                
                pipeline = null;
                
                result = true;
            }
            catch (Exception) {
                //
// Console.WriteLine("The runspace could not be disposed. {0}", eClosingRunspace.Message);
            }
            return result;
        }
Esempio n. 23
0
        protected void CreateHelpersForSpecifiedRunspaces()
        {
            RemoteRunspace[] remoteRunspaces;
            Pipeline[] pipelines;

            // extract RemoteRunspace out of the PSSession objects
            int length = Session.Length;
            remoteRunspaces = new RemoteRunspace[length];

            for (int i = 0; i < length; i++)
            {
                remoteRunspaces[i] = (RemoteRunspace)Session[i].Runspace;
            }

            // create the set of pipelines from the RemoteRunspace objects and 
            // create IREHelperRunspace helper class to create operations
            pipelines = new Pipeline[length];

            for (int i = 0; i < length; i++)
            {
                pipelines[i] = CreatePipeline(remoteRunspaces[i]);

                // create the operation object
                IThrottleOperation operation = new ExecutionCmdletHelperRunspace(pipelines[i]);
                Operations.Add(operation);
            }
        } // CreateHelpersForSpecifiedRunspaces
Esempio n. 24
0
 internal void StopNestedPipelines(Pipeline pipeline)
 {
     List<Pipeline> list = null;
     lock (this._runningPipelines.SyncRoot)
     {
         if (!this._runningPipelines.Contains(pipeline) || (this.GetCurrentlyRunningPipeline() == pipeline))
         {
             return;
         }
         list = new List<Pipeline>();
         for (int i = this._runningPipelines.Count - 1; i >= 0; i--)
         {
             if (this._runningPipelines[i] == pipeline)
             {
                 break;
             }
             list.Add((Pipeline) this._runningPipelines[i]);
         }
     }
     if (list != null)
     {
         foreach (Pipeline pipeline2 in list)
         {
             try
             {
                 pipeline2.Stop();
             }
             catch (InvalidPipelineStateException)
             {
             }
         }
     }
 }
Esempio n. 25
0
 public string ExecuteCommand(string command)
 {
     pipeline = Runspace.CreatePipeline(command, true);
     return executePipeline();
 }
Esempio n. 26
0
 internal void RemoveFromRunningPipelineList(PipelineBase pipeline)
 {
     lock (this._runningPipelines.SyncRoot)
     {
         this._runningPipelines.Remove(pipeline);
         if (this._runningPipelines.Count == 0)
         {
             this.currentlyRunningPipeline = null;
         }
         else
         {
             this.currentlyRunningPipeline = (Pipeline) this._runningPipelines[this._runningPipelines.Count - 1];
         }
         pipeline.PipelineFinishedEvent.Set();
     }
 }
Esempio n. 27
0
 internal void AddToRunningPipelineList(PipelineBase pipeline)
 {
     lock (this._runningPipelines.SyncRoot)
     {
         if (!this._bypassRunspaceStateCheck && (this.RunspaceState != System.Management.Automation.Runspaces.RunspaceState.Opened))
         {
             InvalidRunspaceStateException exception = new InvalidRunspaceStateException(StringUtil.Format(RunspaceStrings.RunspaceNotOpenForPipeline, this.RunspaceState.ToString()), this.RunspaceState, System.Management.Automation.Runspaces.RunspaceState.Opened);
             throw exception;
         }
         this._runningPipelines.Add(pipeline);
         this.currentlyRunningPipeline = pipeline;
     }
 }
Esempio n. 28
0
        private void InvokeCoreAsync(Pipeline pipeline, IEnumerable<object> inputs, EventHandler<PipelineStateEventArgs> pipelineStateChanged)
        {
            bool hadTheLockAlready = IHaveTheLock;

            pipeline.StateChanged += (sender, e) =>
            {
                // Release the lock ASAP
                bool finished = e.PipelineStateInfo.State == PipelineState.Completed ||
                                e.PipelineStateInfo.State == PipelineState.Failed ||
                                e.PipelineStateInfo.State == PipelineState.Stopped;
                if (finished && !hadTheLockAlready)
                {
                    // Release the dispatcher lock
                    _dispatcherLock.Release();
                }

                pipelineStateChanged.Raise(sender, e);

                // Dispose Pipeline object upon completion
                if (finished)
                {
                    ((Pipeline)sender).Dispose();
                }
            };

            if (inputs != null)
            {
                foreach (var input in inputs)
                {
                    pipeline.Input.Write(input);
                }
            }

            // Take the dispatcher lock and invoke the pipeline
            // REVIEW: This could probably be done in a Task so that we can return to the caller before even taking the dispatcher lock
            if (IHaveTheLock)
            {
                pipeline.InvokeAsync();
            }
            else
            {
                _dispatcherLock.Wait();
                try
                {
                    IHaveTheLock = true;
                    pipeline.InvokeAsync();
                }
                catch
                {
                    // Don't care about the exception, rethrow it, but first release the lock
                    IHaveTheLock = false;
                    _dispatcherLock.Release();
                    throw;
                }
            }
        }
Esempio n. 29
0
 public string ExecuteScripts(IEnumerable<string> scripts)
 {
     var scriptStr = string.Join(Environment.NewLine, scripts);
     pipeline = Runspace.CreatePipeline(scriptStr);
     return executePipeline();
 }
Esempio n. 30
0
 public Pipeline(System.Management.Automation.Runspaces.Pipeline pipeline)
 {
     this.pipeline = pipeline;
 }
Esempio n. 31
0
 private void InitializePS(ref OperationResult Result, Pipeline pipeline)
 {
     Command initProcess = new Command("Import-Module");
     initProcess.Parameters.Add("Name", "ActiveDirectory");
     pipeline.Commands.Add(initProcess);
     try
     {
         pipeline.Invoke();
         Result.Status = Statics.Result.Success;
     }
     catch (Exception ex)
     {
         if (!ex.Message.Contains("Unable to find a default server with Active Directory Web Services"))
         {
             Result.Status = Statics.Result.Error;
             Result.Errors.Add(ex.Message);
         }
         else
         {
             Result.Status = Statics.Result.Success;
         }
     }
 }
Esempio n. 32
0
 private Collection<PSObject> InvokeCore(Pipeline pipeline, IEnumerable<object> inputs)
 {
     Collection<PSObject> output = null;
     WithLock(() =>
     {
         output = inputs == null ? pipeline.Invoke() : pipeline.Invoke(inputs);
     });
     return output;
 }