本文整理汇总了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();
}
}
示例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();
}
}
}
示例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");
}
}
示例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;
}
示例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;
}
示例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");
}
}
示例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);
}
示例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);
}
}
}
示例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;
}
示例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>();
}
示例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);
}
示例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;
}
}
}
示例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));
}
}
示例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));
}
}
示例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;
}