当前位置: 首页>>代码示例>>C#>>正文


C# PSDataCollection类代码示例

本文整理汇总了C#中PSDataCollection的典型用法代码示例。如果您正苦于以下问题:C# PSDataCollection类的具体用法?C# PSDataCollection怎么用?C# PSDataCollection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


PSDataCollection类属于命名空间,在下文中一共展示了PSDataCollection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        /// <summary>
        /// This sample uses the PowerShell class to execute
        /// a script that generates the numbers from 1 to 10 with delays
        /// between each number. It uses the asynchronous capabilities of
        /// the pipeline to manage the execution of the pipeline and
        /// retrieve results as soon as they are available from a
        /// a script.
        /// </summary>
        /// <param name="args">Unused</param>
        /// <remarks>
        /// This sample demonstrates the following:
        /// 1. Creating instances of the PowerShell class.
        /// 2. Using these instances to execute a string as a PowerShell script.
        /// 3. Using the BeginInvoke method and the events on the PowerShell and
        ///    output pipe classes to process script output asynchronously.
        /// 4. Using the PowerShell Stop() method to interrupt an executing pipeline.
        /// </remarks>
        static void Main(string[] args)
        {
            Console.WriteLine("Print the numbers from 1 to 10. Hit any key to halt processing\n");

            PowerShell powershell = PowerShell.Create();

            // Create a pipeline with a script that generates the numbers from 1 to 10. One
            // number is generated every half second.
            powershell.AddScript("1..10 | foreach {$_ ; start-sleep -milli 500}");

            // Add the event handlers.  If we didn't care about hooking the DataAdded
            // event, we would let BeginInvoke create the output stream for us.
            PSDataCollection<PSObject> output = new PSDataCollection<PSObject>();
            output.DataAdded += new EventHandler<DataAddedEventArgs>(Output_DataAdded);
            powershell.InvocationStateChanged += new EventHandler<PSInvocationStateChangedEventArgs>(Powershell_InvocationStateChanged);

            IAsyncResult asyncResult = powershell.BeginInvoke<PSObject, PSObject>(null, output);

            // Wait for things to happen. If the user hits a key before the
            // pipeline has completed, then call the PowerShell Stop() method
            // to halt processing.
            Console.ReadKey();
            if (powershell.InvocationStateInfo.State != PSInvocationState.Completed)
            {
                // Stop the pipeline...
                Console.WriteLine("\nStopping the pipeline!\n");
                powershell.Stop();

                // Wait for the PowerShell state change messages to be displayed...
                System.Threading.Thread.Sleep(500);
                Console.WriteLine("\nPress a key to exit");
                Console.ReadKey();
            }
        }
开发者ID:dgrapp1,项目名称:WindowsSDK7-Samples,代码行数:51,代码来源:Runspace09.cs

示例2: Execute

        public PSObject Execute(string script)
        {
            using (Runspace runspace = CreateRunspace())
              {
            runspace.Open();

            using (var powerShell = System.Management.Automation.PowerShell.Create())
            {
              powerShell.Runspace = runspace;

              powerShell.AddScript(script);

              powerShell.Streams.Error.DataAdded += OnError;
              powerShell.Streams.Debug.DataAdded += OnDebug;
              powerShell.Streams.Warning.DataAdded += OnWarning;
              powerShell.Streams.Progress.DataAdded += OnProgress;
              powerShell.Streams.Verbose.DataAdded += OnVerbose;

              var outputCollection = new PSDataCollection<PSObject>();

              outputCollection.DataAdded += OnOutput;

              IAsyncResult invokeResult = powerShell.BeginInvoke<PSObject, PSObject>(null, outputCollection);

              powerShell.EndInvoke(invokeResult);

              if (_errorCount != 0)
              {
            throw new PowerShellScriptExecutionException(powerShell.Streams.Error);
              }

              return outputCollection.LastOrDefault();
            }
              }
        }
开发者ID:spawluk,项目名称:UberDeployer,代码行数:35,代码来源:PowerShellExecutor.cs

示例3: DirectExecutionActivitiesCommandRuntime

		public DirectExecutionActivitiesCommandRuntime(PSDataCollection<PSObject> output, ActivityImplementationContext implementationContext, Type cmdletType)
		{
			if (output != null)
			{
				if (implementationContext != null)
				{
					if (cmdletType != null)
					{
						this._output = output;
						this._implementationContext = implementationContext;
						this._cmdletType = cmdletType;
						return;
					}
					else
					{
						throw new ArgumentNullException("cmdletType");
					}
				}
				else
				{
					throw new ArgumentNullException("implementationContext");
				}
			}
			else
			{
				throw new ArgumentNullException("output");
			}
		}
开发者ID:nickchal,项目名称:pash,代码行数:28,代码来源:DirectExecutionActivitiesCommandRuntime.cs

示例4: ServerSteppablePipelineDriver

 internal ServerSteppablePipelineDriver(PowerShell powershell, bool noInput, Guid clientPowerShellId, Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, ApartmentState apartmentState, HostInfo hostInfo, System.Management.Automation.RemoteStreamOptions streamOptions, bool addToHistory, Runspace rsToUse, ServerSteppablePipelineSubscriber eventSubscriber, PSDataCollection<object> powershellInput)
 {
     this.localPowerShell = powershell;
     this.clientPowerShellId = clientPowerShellId;
     this.clientRunspacePoolId = clientRunspacePoolId;
     this.remoteStreamOptions = streamOptions;
     this.apartmentState = apartmentState;
     this.noInput = noInput;
     this.addToHistory = addToHistory;
     this.eventSubscriber = eventSubscriber;
     this.powershellInput = powershellInput;
     this.input = new PSDataCollection<object>();
     this.inputEnumerator = this.input.GetEnumerator();
     this.input.ReleaseOnEnumeration = true;
     this.dsHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, this.remoteStreamOptions, null);
     this.remoteHost = this.dsHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost);
     this.dsHandler.InputEndReceived += new EventHandler(this.HandleInputEndReceived);
     this.dsHandler.InputReceived += new EventHandler<RemoteDataEventArgs<object>>(this.HandleInputReceived);
     this.dsHandler.StopPowerShellReceived += new EventHandler(this.HandleStopReceived);
     this.dsHandler.HostResponseReceived += new EventHandler<RemoteDataEventArgs<RemoteHostResponse>>(this.HandleHostResponseReceived);
     this.dsHandler.OnSessionConnected += new EventHandler(this.HandleSessionConnected);
     if (rsToUse == null)
     {
         throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings", "NestedPipelineMissingRunspace", new object[0]);
     }
     this.localPowerShell.Runspace = rsToUse;
     eventSubscriber.SubscribeEvents(this);
     this.stateOfSteppablePipeline = PSInvocationState.NotStarted;
 }
开发者ID:nickchal,项目名称:pash,代码行数:29,代码来源:ServerSteppablePipelineDriver.cs

示例5: ContainerParentJob

 public ContainerParentJob(string command, string name, JobIdentifier jobId, string jobType) : base(command, name, jobId)
 {
     this._moreData = true;
     this._tracer = PowerShellTraceSourceFactory.GetTraceSource();
     this._executionError = new PSDataCollection<ErrorRecord>();
     base.PSJobTypeName = jobType;
 }
开发者ID:nickchal,项目名称:pash,代码行数:7,代码来源:ContainerParentJob.cs

示例6: BeginInvokePowerShell

		internal IAsyncResult BeginInvokePowerShell(System.Management.Automation.PowerShell command, PSDataCollection<PSObject> input, PSDataCollection<PSObject> output, PSActivityEnvironment policy, AsyncCallback callback, object state)
		{
			if (command != null)
			{
				ConnectionAsyncResult connectionAsyncResult = new ConnectionAsyncResult(state, callback, command.InstanceId);
				this._structuredTracer.OutOfProcessRunspaceStarted(command.ToString());
				ActivityInvoker activityInvoker = new ActivityInvoker();
				activityInvoker.Input = input;
				activityInvoker.Output = output;
				activityInvoker.Policy = policy;
				activityInvoker.PowerShell = command;
				activityInvoker.AsyncResult = connectionAsyncResult;
				ActivityInvoker activityInvoker1 = activityInvoker;
				connectionAsyncResult.Invoker = activityInvoker1;
				this._requests.Enqueue(activityInvoker1);
				PSOutOfProcessActivityController.PerfCountersMgr.UpdateCounterByValue(PSWorkflowPerformanceCounterSetInfo.CounterSetId, 19, (long)1, true);
				PSOutOfProcessActivityController.PerfCountersMgr.UpdateCounterByValue(PSWorkflowPerformanceCounterSetInfo.CounterSetId, 20, (long)1, true);
				this.CheckAndStartServicingThread();
				return connectionAsyncResult;
			}
			else
			{
				throw new ArgumentNullException("command");
			}
		}
开发者ID:nickchal,项目名称:pash,代码行数:25,代码来源:PSOutOfProcessActivityController.cs

示例7: RemotePipeline

        /// <summary>
        /// Private constructor that does most of the work constructing a remote pipeline object.
        /// </summary>
        /// <param name="runspace">RemoteRunspace object</param>
        /// <param name="addToHistory">AddToHistory</param>
        /// <param name="isNested">IsNested</param>
        private RemotePipeline(RemoteRunspace runspace, bool addToHistory, bool isNested)
            : base(runspace)
        {
            _addToHistory = addToHistory;
            _isNested = isNested;
            _isSteppable = false;
            _runspace = runspace;
            _computerName = ((RemoteRunspace)_runspace).ConnectionInfo.ComputerName;
            _runspaceId = _runspace.InstanceId;

            //Initialize streams
            _inputCollection = new PSDataCollection<object>();
            _inputCollection.ReleaseOnEnumeration = true;

            _inputStream = new PSDataCollectionStream<object>(Guid.Empty, _inputCollection);
            _outputCollection = new PSDataCollection<PSObject>();
            _outputStream = new PSDataCollectionStream<PSObject>(Guid.Empty, _outputCollection);
            _errorCollection = new PSDataCollection<ErrorRecord>();
            _errorStream = new PSDataCollectionStream<ErrorRecord>(Guid.Empty, _errorCollection);

            // Create object stream for method executor objects.
            MethodExecutorStream = new ObjectStream();
            IsMethodExecutorStreamEnabled = false;

            SetCommandCollection(_commands);

            //Create event which will be signalled when pipeline execution
            //is completed/failed/stoped. 
            //Note:Runspace.Close waits for all the running pipeline
            //to finish.  This Event must be created before pipeline is 
            //added to list of running pipelines. This avoids the race condition
            //where Close is called after pipeline is added to list of 
            //running pipeline but before event is created.
            PipelineFinishedEvent = new ManualResetEvent(false);
        }
开发者ID:40a,项目名称:PowerShell,代码行数:41,代码来源:remotepipeline.cs

示例8: ExecuteScript

        public void ExecuteScript(ScriptConfigElement e)
        {
            using (_instance = PowerShell.Create())
            {
                _instance.AddScript(File.ReadAllText(e.PathToScript));

                PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
                outputCollection.DataAdded += outputCollection_DataAdded;
                _instance.Streams.Progress.DataAdded += Progress_DataAdded;
                _instance.Streams.Error.DataAdded += Error_DataAdded;
                _instance.Streams.Verbose.DataAdded += Verbose_DataAdded;
                _instance.Streams.Debug.DataAdded += Debug_DataAdded;
                _instance.Streams.Warning.DataAdded += Warning_DataAdded;

                IAsyncResult result = _instance.BeginInvoke<PSObject, PSObject>(null,
                    outputCollection);

                while (result.IsCompleted == false)
                {
                    Thread.Sleep(500);
                }

                foreach (PSObject o in outputCollection)
                {
                    Console.WriteLine(o.GetType());
                    Console.WriteLine(o);
                }
            }
        }
开发者ID:ClearMeasure,项目名称:PowerShellRunnerService,代码行数:29,代码来源:PowerShellRunner.cs

示例9: ExtractErrorFromErrorRecord

        public static string ExtractErrorFromErrorRecord(this Runspace runspace, ErrorRecord record)
        {
            Pipeline pipeline = runspace.CreatePipeline("$input", false);
            pipeline.Commands.Add("out-string");

            Collection<PSObject> result;
            using (PSDataCollection<object> inputCollection = new PSDataCollection<object>())
            {
                inputCollection.Add(record);
                inputCollection.Complete();
                result = pipeline.Invoke(inputCollection);
            }

            if (result.Count > 0)
            {
                string str = result[0].BaseObject as string;
                if (!string.IsNullOrEmpty(str))
                {
                    // Remove \r\n, which is added by the Out-String cmdlet.
                    return str.Substring(0, str.Length - 2);
                }
            }

            return String.Empty;
        }
开发者ID:monoman,项目名称:NugetCracker,代码行数:25,代码来源:RunspaceExtensions.cs

示例10: PSInformationalBuffers

 internal PSInformationalBuffers(Guid psInstanceId)
 {
     this.psInstanceId = psInstanceId;
     this.progress = new PSDataCollection<ProgressRecord>();
     this.verbose = new PSDataCollection<VerboseRecord>();
     this.debug = new PSDataCollection<DebugRecord>();
     this.warning = new PSDataCollection<WarningRecord>();
 }
开发者ID:nickchal,项目名称:pash,代码行数:8,代码来源:PSInformationalBuffers.cs

示例11: BeginInvoke

        /// <summary>
        /// Starts the pipeline script async.
        /// </summary>
        public void BeginInvoke(Queue<PSObject> queue, int count)
        {
            var input = new PSDataCollection<PSObject>(count);
            while (--count >= 0)
                input.Add(queue.Dequeue());
            input.Complete();

            _async = _posh.BeginInvoke(input);
        }
开发者ID:nightroman,项目名称:SplitPipeline,代码行数:12,代码来源:Job.cs

示例12: ServerPowerShellDriver

 internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId, Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, ApartmentState apartmentState, HostInfo hostInfo, System.Management.Automation.RemoteStreamOptions streamOptions, bool addToHistory, Runspace rsToUse)
 {
     this.clientPowerShellId = clientPowerShellId;
     this.clientRunspacePoolId = clientRunspacePoolId;
     this.remoteStreamOptions = streamOptions;
     this.apartmentState = apartmentState;
     this.localPowerShell = powershell;
     this.extraPowerShell = extraPowerShell;
     this.localPowerShellOutput = new PSDataCollection<PSObject>();
     this.noInput = noInput;
     this.addToHistory = addToHistory;
     this.dsHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, this.remoteStreamOptions, this.localPowerShell);
     this.remoteHost = this.dsHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost);
     if (!noInput)
     {
         this.input = new PSDataCollection<object>();
         this.input.ReleaseOnEnumeration = true;
         this.input.IdleEvent += new EventHandler<EventArgs>(this.HandleIdleEvent);
     }
     this.RegisterPipelineOutputEventHandlers(this.localPowerShellOutput);
     if (this.localPowerShell != null)
     {
         this.RegisterPowerShellEventHandlers(this.localPowerShell);
         this.datasent[0] = false;
     }
     if (extraPowerShell != null)
     {
         this.RegisterPowerShellEventHandlers(extraPowerShell);
         this.datasent[1] = false;
     }
     this.RegisterDataStructureHandlerEventHandlers(this.dsHandler);
     if (rsToUse != null)
     {
         this.localPowerShell.Runspace = rsToUse;
         if (extraPowerShell != null)
         {
             extraPowerShell.Runspace = rsToUse;
         }
     }
     else
     {
         this.localPowerShell.RunspacePool = runspacePoolDriver.RunspacePool;
         if (extraPowerShell != null)
         {
             extraPowerShell.RunspacePool = runspacePoolDriver.RunspacePool;
         }
     }
 }
开发者ID:nickchal,项目名称:pash,代码行数:48,代码来源:ServerPowerShellDriver.cs

示例13: Update

        public async Task Update(ChocolateyPackageVersion package)
        {
            using (var powershell = PowerShell.Create())
            {
                var command = string.Format("cup {0}", package.Id);

                powershell.AddScript(command);
                powershell.Streams.Error.DataAdded += ErrorDataAdded;
                powershell.Streams.Warning.DataAdded += WarningDataAdded;

                var outputCollection = new PSDataCollection<PSObject>();
                outputCollection.DataAdded += this.SendOutput;
                
                await Task.Factory.StartNew(() => powershell.Invoke(null, outputCollection, null));
            }
        }
开发者ID:mmdurrant,项目名称:ChocolateyExplorer,代码行数:16,代码来源:Installer.cs

示例14: Uninstall

        public async Task Uninstall(ChocolateyPackageVersion package)
        {
            using (var powershell = PowerShell.Create())
            {
                var command = string.Format(
                    "cuninst {0} -version {1}",
                    package.Id,
                    package.Version);

                powershell.AddScript(command);

                var outputCollection = new PSDataCollection<PSObject>();
                outputCollection.DataAdded += this.SendOutput;

                await Task.Factory.StartNew(() => powershell.Invoke(null, outputCollection, null));
            }
        }
开发者ID:mmdurrant,项目名称:ChocolateyExplorer,代码行数:17,代码来源:Installer.cs

示例15: InvokePowerShellScript

        private async Task<PSDataCollection<ErrorRecord>> InvokePowerShellScript(Dictionary<string, string> envVars, TraceWriter traceWriter)
        {
            InitialSessionState iss = InitialSessionState.CreateDefault();
            PSDataCollection<ErrorRecord> errors = new PSDataCollection<ErrorRecord>();

            using (Runspace runspace = RunspaceFactory.CreateRunspace(iss))
            {
                runspace.Open();
                SetRunspaceEnvironmentVariables(runspace, envVars);
                RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
                runSpaceInvoker.Invoke("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted");

                using (
                    System.Management.Automation.PowerShell powerShellInstance =
                        System.Management.Automation.PowerShell.Create())
                {
                    powerShellInstance.Runspace = runspace;
                    _moduleFiles = GetModuleFilePaths(_host.ScriptConfig.RootScriptPath, _functionName);
                    if (_moduleFiles.Any())
                    {
                        powerShellInstance.AddCommand("Import-Module").AddArgument(_moduleFiles);
                        LogLoadedModules();
                    }

                    _script = GetScript(_scriptFilePath);
                    powerShellInstance.AddScript(_script, true);

                    PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
                    outputCollection.DataAdded += (sender, e) => OutputCollectionDataAdded(sender, e, traceWriter);

                    powerShellInstance.Streams.Error.DataAdded += (sender, e) => ErrorDataAdded(sender, e, traceWriter);

                    IAsyncResult result = powerShellInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection);
                    await Task.Factory.FromAsync<PSDataCollection<PSObject>>(result, powerShellInstance.EndInvoke);

                    foreach (ErrorRecord errorRecord in powerShellInstance.Streams.Error)
                    {
                        errors.Add(errorRecord);
                    }
                }

                runspace.Close();
            }

            return errors;
        }
开发者ID:Azure,项目名称:azure-webjobs-sdk-script,代码行数:46,代码来源:PowerShellFunctionInvoker.cs


注:本文中的PSDataCollection类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。