• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# PSDataCollection类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: Install

        public async Task Install(ChocolateyPackageVersion package, string arguments, CancellationToken cancellationToken)
        {
            var args = string.IsNullOrEmpty(arguments) ? string.Empty : " -installArguments " + arguments;

            using (var powershell = PowerShell.Create())
            {
                var command = string.Format(
                    "cinst {0} -version {1}{2}",
                    package.Id,
                    package.Version,
                    args);

                powershell.AddScript(command);

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

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


示例17: RunScript

        private async Task RunScript()
        {
            if (!File.Exists(Name))
            {
                return;
            }
            if (Type.Equals("Powershell"))
            {
                using (var powerShellInstance = PowerShell.Create())
                {
                    var scriptContents = File.ReadAllText(Name);
                    powerShellInstance.AddScript(scriptContents);
                    // prepare a new collection to store output stream objects
                    var outputCollection = new PSDataCollection<PSObject>();
                    outputCollection.DataAdded += outputCollection_DataAdded;
                    powerShellInstance.Streams.Error.DataAdded += Error_DataAdded;
                    // begin invoke execution on the pipeline
                    // use this overload to specify an output stream buffer
                    var result = powerShellInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection);
                    while (result.IsCompleted == false)
                    {
                        Thread.Sleep(1000);
                    }
                    await
                        Console.Out.WriteLineAsync("Execution has stopped. The pipeline state: " +
                                                   powerShellInstance.InvocationStateInfo.State);
                }
            }
            else if (Type.Equals("cmd"))
            {
                try
                {
                    await RunProcessAsync(Name);
                }
                catch (Exception ex)
                {

                    Console.WriteLine(ex.Message);
                }
            }
        }
开发者ID:Ulterius,项目名称:server,代码行数:41,代码来源:JobModel.cs


示例18: ExecuteCommand

        public static void ExecuteCommand(String command, PSHost host)
        {
            Console.WriteLine("Executing command:");

            string outputLine = command;
            int ichNewline = command.IndexOfAny("\r\n".ToCharArray());
            if (ichNewline > 0)
                outputLine = command.Substring(0, ichNewline);

            Console.WriteLine(outputLine);

            using (Runspace space = RunspaceFactory.CreateRunspace(host))
            {
                space.Open();
                using (PowerShell ps = PowerShell.Create())
                {
                    ps.Runspace = space;
                    ps.AddScript(command);

                    // Create the output buffer for the results.
                    PSDataCollection<PSObject> output = new PSDataCollection<PSObject>();
                    IAsyncResult async = ps.BeginInvoke();
                    foreach (PSObject result in ps.EndInvoke(async))
                    {
                        Console.WriteLine(result.ToString());
                    }

                    PSDataStreams streams = ps.Streams;

                    if (streams.Error != null)
                    {
                        foreach (ErrorRecord record in streams.Error)
                        {
                            Console.WriteLine(GetMessageFromErrorRecord(record));
                            throw record.Exception;
                        }
                    }
                }
            }
        }
开发者ID:dineshkummarc,项目名称:Windows-Azure-CouchDB,代码行数:40,代码来源:ExecuteCommands.cs


示例19: CopyNodeJSExe

        public string CopyNodeJSExe()
        {
            string azureCouchDBInstallFolder;

            azureCouchDBInstallFolder = General.Instance.GetAzureCouchDBInstallFolder();

            try
            {
                if (Directory.Exists(AzureNodeJSSdkBinPath) == false)
                {
                    throw new Exception("Node js not installed.");
                }

                string destination = Path.Combine(azureCouchDBInstallFolder, @"WorkerRole\Node\bin");
                if (Directory.Exists(destination) == false)
                {
                    Directory.CreateDirectory(destination);
                }

                string nodeExeLocation = Path.Combine(AzureNodeJSSdkBinPath, "node.exe");

                using (PowerShell ps = PowerShell.Create())
                {
                    ps.AddScript(String.Format("COPY-ITEM \"{0}\" \"{1}\" ", nodeExeLocation, destination));
                    PSDataCollection<PSObject> output = new PSDataCollection<PSObject>();
                    IAsyncResult async = ps.BeginInvoke();
                    foreach (PSObject result in ps.EndInvoke(async))
                    {
                        Console.WriteLine(result.ToString());
                    }
                }
            }
            catch
            {
                return "Error copying Node executable.";
            }
            return "Node Executable copied Successfully.";
        }
开发者ID:dineshkummarc,项目名称:Windows-Azure-CouchDB,代码行数:38,代码来源:GetNodeJSExecutables.cs


示例20: ReportException

        /// <summary>
        /// To display an exception using the display formatter, 
        /// run a second pipeline passing in the error record.
        /// The runtime will bind this to the $input variable,
        /// which is why $input is being piped to the Out-String
        /// cmdlet. The WriteErrorLine method is called to make sure 
        /// the error gets displayed in the correct error color.
        /// </summary>
        /// <param name="e">The exception to display.</param>
        private void ReportException(Exception e)
        {
            if (e != null)
            {
                object error;
                IContainsErrorRecord icer = e as IContainsErrorRecord;
                if (icer != null)
                {
                    error = icer.ErrorRecord;
                }
                else
                {
                    error = (object)new ErrorRecord(e, "Host.ReportException", ErrorCategory.NotSpecified, null);
                }

                lock (this.instanceLock)
                {
                    this.currentPowerShell = PowerShell.Create();
                }

                this.currentPowerShell.Runspace = this.myRunSpace;

                try
                {
                    this.currentPowerShell.AddScript("$input").AddCommand("out-string");

                    // Do not merge errors, this function will swallow errors.
                    Collection<PSObject> result;
                    PSDataCollection<object> inputCollection = new PSDataCollection<object>();
                    inputCollection.Add(error);
                    inputCollection.Complete();
                    result = this.currentPowerShell.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.
                            this.myHost.UI.WriteErrorLine(str.Substring(0, str.Length - 2));
                        }
                    }
                }
                finally
                {
                    // Dispose of the pipeline and set it to null, locking it  because
                    // currentPowerShell may be accessed by the ctrl-C handler.
                    lock (this.instanceLock)
                    {
                        this.currentPowerShell.Dispose();
                        this.currentPowerShell = null;
                    }
                }
            }
        }
开发者ID:dbremner,项目名称:Win81Desktop,代码行数:64,代码来源:Host06.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# PSPDEV类代码示例发布时间:2022-05-24
下一篇:
C# PRoConClient类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap