本文整理汇总了C#中PSDataCollection.ReadAll方法的典型用法代码示例。如果您正苦于以下问题:C# PSDataCollection.ReadAll方法的具体用法?C# PSDataCollection.ReadAll怎么用?C# PSDataCollection.ReadAll使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PSDataCollection
的用法示例。
在下文中一共展示了PSDataCollection.ReadAll方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AggregateJobResults
private void AggregateJobResults(PSDataCollection<PSStreamObject> resultsCollection)
{
lock (this._myLock)
{
if ((this._disposed || this._stoppedMonitoringAllJobs) || (this._aggregatedResults.IsAddingCompleted || this._cancellationTokenSource.IsCancellationRequested))
{
return;
}
}
foreach (PSStreamObject obj2 in resultsCollection.ReadAll())
{
bool flag = false;
try
{
lock (this._myLock)
{
if ((!this._disposed && !this._stoppedMonitoringAllJobs) && (!this._aggregatedResults.IsAddingCompleted && !this._cancellationTokenSource.IsCancellationRequested))
{
this._aggregatedResults.Add(obj2, this._cancellationTokenSource.Token);
flag = true;
}
}
}
catch (Exception)
{
}
if (!flag)
{
this.StopMonitoringJob(this._throttlingJob);
try
{
this._throttlingJob.Results.Add(obj2);
}
catch (InvalidOperationException)
{
}
}
}
}
示例2: ProcessCommand
/// <summary>
/// Process debugger command.
/// </summary>
/// <param name="command">Debugger PSCommand</param>
/// <param name="output">Output</param>
/// <returns>DebuggerCommandResults</returns>
public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataCollection<PSObject> output)
{
CheckForValidateState();
_detachCommand = false;
if (command == null)
{
throw new PSArgumentNullException("command");
}
if (output == null)
{
throw new PSArgumentNullException("output");
}
if (!DebuggerStopped)
{
throw new PSInvalidOperationException(
DebuggerStrings.CannotProcessDebuggerCommandNotStopped,
null,
Debugger.CannotProcessCommandNotStopped,
ErrorCategory.InvalidOperation,
null);
}
DebuggerCommandResults results = null;
// Execute command on server.
bool executionError = false;
using (_psDebuggerCommand = GetNestedPowerShell())
{
foreach (var cmd in command.Commands)
{
cmd.MergeMyResults(PipelineResultTypes.All, PipelineResultTypes.Output);
_psDebuggerCommand.AddCommand(cmd);
}
PSDataCollection<PSObject> internalOutput = new PSDataCollection<PSObject>();
internalOutput.DataAdded += (sender, args) =>
{
foreach (var item in internalOutput.ReadAll())
{
if (item == null) { return; }
DebuggerCommand dbgCmd = item.BaseObject as DebuggerCommand;
if (dbgCmd != null)
{
bool executedByDebugger = (dbgCmd.ResumeAction != null || dbgCmd.ExecutedByDebugger);
results = new DebuggerCommandResults(dbgCmd.ResumeAction, executedByDebugger);
}
else if (item.BaseObject is DebuggerCommandResults)
{
results = item.BaseObject as DebuggerCommandResults;
}
else
{
output.Add(item);
}
}
};
try
{
_psDebuggerCommand.Invoke(null, internalOutput, null);
}
catch (Exception e)
{
CommandProcessor.CheckForSevereException(e);
executionError = true;
RemoteException re = e as RemoteException;
if ((re != null) && (re.ErrorRecord != null))
{
// Allow the IncompleteParseException to throw so that the console
// can handle here strings and continued parsing.
if (re.ErrorRecord.CategoryInfo.Reason == typeof(IncompleteParseException).Name)
{
throw new IncompleteParseException(
(re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : null,
re.ErrorRecord.FullyQualifiedErrorId);
}
// Allow the RemoteException and InvalidRunspacePoolStateException to propagate so that the host can
// clean up the debug session.
if ((re.ErrorRecord.CategoryInfo.Reason == typeof(InvalidRunspacePoolStateException).Name) ||
(re.ErrorRecord.CategoryInfo.Reason == typeof(RemoteException).Name))
{
throw new PSRemotingTransportException(
(re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : string.Empty);
}
}
// Allow all PSRemotingTransportException and RemoteException errors to propagate as this
// indicates a broken debug session.
//.........这里部分代码省略.........
示例3: ServerPowerShellDriver
/// <summary>
/// Default constructor for creating ServerPowerShellDrivers
/// </summary>
/// <param name="powershell">decoded powershell object</param>
/// <param name="extraPowerShell">extra pipeline to be run after <paramref name="powershell"/> completes</param>
/// <param name="noInput">whether there is input for this powershell</param>
/// <param name="clientPowerShellId">the client powershell id</param>
/// <param name="clientRunspacePoolId">the client runspacepool id</param>
/// <param name="runspacePoolDriver">runspace pool driver
/// which is creating this powershell driver</param>
/// <param name="apartmentState">apartment state for this powershell</param>
/// <param name="hostInfo">host info using which the host for
/// this powershell will be constructed</param>
/// <param name="streamOptions">serialization options for the streams in this powershell</param>
/// <param name="addToHistory">
/// true if the command is to be added to history list of the runspace. false, otherwise.
/// </param>
/// <param name="rsToUse">
/// If not null, this Runspace will be used to invoke Powershell.
/// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used.
/// </param>
/// <param name="output">
/// If not null, this is used as another source of output sent to the client.
/// </param>
internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId,
Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver,
ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions,
bool addToHistory, Runspace rsToUse, PSDataCollection<PSObject> output)
#endif
{
InstanceId = clientPowerShellId;
RunspacePoolId = clientRunspacePoolId;
RemoteStreamOptions = streamOptions;
#if !CORECLR // No ApartmentState In CoreCLR
this.apartmentState = apartmentState;
#endif
LocalPowerShell = powershell;
_extraPowerShell = extraPowerShell;
_localPowerShellOutput = new PSDataCollection<PSObject>();
_noInput = noInput;
_addToHistory = addToHistory;
_psDriverInvoker = runspacePoolDriver;
DataStructureHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, RemoteStreamOptions, LocalPowerShell);
_remoteHost = DataStructureHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost);
if (!noInput)
{
InputCollection = new PSDataCollection<object>();
InputCollection.ReleaseOnEnumeration = true;
InputCollection.IdleEvent += new EventHandler<EventArgs>(HandleIdleEvent);
}
RegisterPipelineOutputEventHandlers(_localPowerShellOutput);
if (LocalPowerShell != null)
{
RegisterPowerShellEventHandlers(LocalPowerShell);
_datasent[0] = false;
}
if (extraPowerShell != null)
{
RegisterPowerShellEventHandlers(extraPowerShell);
_datasent[1] = false;
}
RegisterDataStructureHandlerEventHandlers(DataStructureHandler);
// set the runspace pool and invoke this powershell
if (null != rsToUse)
{
LocalPowerShell.Runspace = rsToUse;
if (extraPowerShell != null)
{
extraPowerShell.Runspace = rsToUse;
}
}
else
{
LocalPowerShell.RunspacePool = runspacePoolDriver.RunspacePool;
if (extraPowerShell != null)
{
extraPowerShell.RunspacePool = runspacePoolDriver.RunspacePool;
}
}
if (output != null)
{
output.DataAdded += (sender, args) =>
{
if (_localPowerShellOutput.IsOpen)
{
var items = output.ReadAll();
foreach (var item in items)
{
_localPowerShellOutput.Add(item);
}
}
};
//.........这里部分代码省略.........
示例4: AggregateJobResults
private void AggregateJobResults(PSDataCollection<PSStreamObject> resultsCollection)
{
lock (_myLock)
{
// try not to remove results from a job, unless it seems safe ...
if (_disposed || _stoppedMonitoringAllJobs || _aggregatedResults.IsAddingCompleted || _cancellationTokenSource.IsCancellationRequested)
{
return;
}
}
// ... and after removing the results via ReadAll, we have to make sure that we don't drop them ...
foreach (var result in resultsCollection.ReadAll())
{
bool successfullyAggregatedResult = false;
try
{
lock (_myLock)
{
// try not to remove results from a job, unless it seems safe ...
if (!(_disposed || _stoppedMonitoringAllJobs || _aggregatedResults.IsAddingCompleted || _cancellationTokenSource.IsCancellationRequested))
{
_aggregatedResults.Add(result, _cancellationTokenSource.Token);
successfullyAggregatedResult = true;
}
}
}
catch (Exception) // BlockingCollection.Add can throw undocumented exceptions - we cannot just catch InvalidOperationException
{
}
// ... so if _aggregatedResults is not accepting new results, we will store them in the throttling job
if (!successfullyAggregatedResult)
{
this.StopMonitoringJob(_throttlingJob);
try
{
_throttlingJob.Results.Add(result);
}
catch (InvalidOperationException)
{
Dbg.Assert(false, "ThrottlingJob.Results was already closed when trying to preserve results aggregated by ForwardingHelper");
}
}
}
}
示例5: ProcessCommand
/// <summary>
/// ProcessCommand
/// </summary>
/// <param name="command">PowerShell command</param>
/// <param name="output">Output</param>
/// <returns>DebuggerCommandResults</returns>
public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataCollection<PSObject> output)
{
if (command == null)
{
throw new PSArgumentNullException("command");
}
if (output == null)
{
throw new PSArgumentNullException("output");
}
if (!DebuggerStopped)
{
throw new PSInvalidOperationException(
DebuggerStrings.CannotProcessDebuggerCommandNotStopped,
null,
Debugger.CannotProcessCommandNotStopped,
ErrorCategory.InvalidOperation,
null);
}
//
// Allow an active pushed debugger to process commands
//
DebuggerCommandResults results = ProcessCommandForActiveDebugger(command, output);
if (results != null)
{
return results;
}
//
// Otherwise let root script debugger handle it.
//
LocalRunspace localRunspace = _context.CurrentRunspace as LocalRunspace;
if (localRunspace == null)
{
throw new PSInvalidOperationException(
DebuggerStrings.CannotProcessDebuggerCommandNotStopped,
null,
Debugger.CannotProcessCommandNotStopped,
ErrorCategory.InvalidOperation,
null);
}
try
{
using (_psDebuggerCommand = PowerShell.Create())
{
if (localRunspace.GetCurrentlyRunningPipeline() != null)
{
_psDebuggerCommand.SetIsNested(true);
}
_psDebuggerCommand.Runspace = localRunspace;
_psDebuggerCommand.Commands = command;
foreach (var cmd in _psDebuggerCommand.Commands.Commands)
{
cmd.MergeMyResults(PipelineResultTypes.All, PipelineResultTypes.Output);
}
PSDataCollection<PSObject> internalOutput = new PSDataCollection<PSObject>();
internalOutput.DataAdded += (sender, args) =>
{
foreach (var item in internalOutput.ReadAll())
{
if (item == null) { continue; }
DebuggerCommand dbgCmd = item.BaseObject as DebuggerCommand;
if (dbgCmd != null)
{
bool executedByDebugger = (dbgCmd.ResumeAction != null || dbgCmd.ExecutedByDebugger);
results = new DebuggerCommandResults(dbgCmd.ResumeAction, executedByDebugger);
}
else
{
output.Add(item);
}
}
};
// Allow any exceptions to propagate.
_psDebuggerCommand.InvokeWithDebugger(null, internalOutput, null, false);
}
}
finally
{
_psDebuggerCommand = null;
}
return results ?? new DebuggerCommandResults(null, false);
}
示例6: DebuggerOnDebuggerStop
private void DebuggerOnDebuggerStop(object sender, DebuggerStopEventArgs args)
{
Debugger debugger = sender as Debugger;
DebuggerResumeAction? resumeAction = null;
DebuggingInBreakpoint = true;
try
{
if (
((ScriptingHostUserInterface) host.UI).CheckSessionCanDoInteractiveAction(
nameof(DebuggerOnDebuggerStop)))
{
var output = new PSDataCollection<PSObject>();
output.DataAdded += (dSender, dArgs) =>
{
foreach (var item in output.ReadAll())
{
host.UI.WriteLine(item.ToString());
}
};
var message = Message.Parse(this, "ise:breakpointhit");
//var position = args.InvocationInfo.DisplayScriptPosition;
IScriptExtent position;
try
{
position = args.InvocationInfo.GetType()
.GetProperty("ScriptPosition",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty)
.GetValue(args.InvocationInfo) as IScriptExtent;
}
catch (Exception)
{
position = args.InvocationInfo.DisplayScriptPosition;
}
if (position != null)
{
message.Arguments.Add("Line", (position.StartLineNumber - 1).ToString());
message.Arguments.Add("Column", (position.StartColumnNumber - 1).ToString());
message.Arguments.Add("EndLine", (position.EndLineNumber - 1).ToString());
message.Arguments.Add("EndColumn", (position.EndColumnNumber - 1).ToString());
}
else
{
message.Arguments.Add("Line", (args.InvocationInfo.ScriptLineNumber - 1).ToString());
message.Arguments.Add("Column", (args.InvocationInfo.OffsetInLine - 1).ToString());
message.Arguments.Add("EndLine", (args.InvocationInfo.ScriptLineNumber).ToString());
message.Arguments.Add("EndColumn", (0).ToString());
}
message.Arguments.Add("HitCount",
args.Breakpoints.Count > 0 ? args.Breakpoints[0].HitCount.ToString() : "1");
SendUiMessage(message);
while (resumeAction == null && !abortRequested)
{
if (ImmediateCommand != null)
{
var psCommand = new PSCommand();
psCommand.AddScript(ImmediateCommand as string)
.AddCommand("Out-Default");
//.AddParameter("Stream", true);
var results = debugger?.ProcessCommand(psCommand, output);
ImmediateResults = output;
if (results?.ResumeAction != null)
{
resumeAction = results.ResumeAction;
}
ImmediateCommand = null;
}
else
{
Thread.Sleep(20);
}
}
args.ResumeAction = resumeAction ?? DebuggerResumeAction.Continue;
}
}
finally
{
DebuggingInBreakpoint = false;
}
}
示例7: Run
/// <summary>
/// Method to run the sample script and handle debugger events.
/// </summary>
public void Run()
{
Console.WriteLine("Starting PowerShell Debugger Sample");
Console.WriteLine();
// Create sample script file to debug.
string fileName = "PowerShellSDKDebuggerSample.ps1";
string filePath = System.IO.Path.Combine(Environment.CurrentDirectory, fileName);
System.IO.File.WriteAllText(filePath, _script);
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
// Open runspace and set debug mode to debug PowerShell scripts and
// Workflow scripts. PowerShell script debugging is enabled by default,
// Workflow debugging is opt-in.
runspace.Open();
runspace.Debugger.SetDebugMode(DebugModes.LocalScript);
using (PowerShell powerShell = PowerShell.Create())
{
powerShell.Runspace = runspace;
// Set breakpoint update event handler. The breakpoint update event is
// raised whenever a break point is added, removed, enabled, or disabled.
// This event is generally used to display current breakpoint information.
runspace.Debugger.BreakpointUpdated += HandlerBreakpointUpdatedEvent;
// Set debugger stop event handler. The debugger stop event is raised
// whenever a breakpoint is hit, or for each script execution sequence point
// when the debugger is in step mode. The debugger remains stopped at the
// current execution location until the event handler returns. When the
// event handler returns it should set the DebuggerStopEventArgs.ResumeAction
// to indicate how the debugger should proceed:
// - Continue Continue execution until next breakpoint is hit.
// - StepInto Step into function.
// - StepOut Step out of function.
// - StepOver Step over function.
// - Stop Stop debugging.
runspace.Debugger.DebuggerStop += HandleDebuggerStopEvent;
// Set initial breakpoint on line 10 of script. This breakpoint
// will be in the script workflow function.
powerShell.AddCommand("Set-PSBreakpoint").AddParameter("Script", filePath).AddParameter("Line", 10);
powerShell.Invoke();
Console.WriteLine("Starting script file: " + filePath);
Console.WriteLine();
// Run script file.
powerShell.Commands.Clear();
powerShell.AddScript(filePath).AddCommand("Out-String").AddParameter("Stream", true);
var scriptOutput = new PSDataCollection<PSObject>();
scriptOutput.DataAdded += (sender, args) =>
{
// Stream script output to console.
foreach (var item in scriptOutput.ReadAll())
{
Console.WriteLine(item);
}
};
powerShell.Invoke<PSObject>(null, scriptOutput);
}
}
// Delete the sample script file.
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
Console.WriteLine("PowerShell Debugger Sample Complete");
Console.WriteLine();
Console.WriteLine("Press any key to exit.");
Console.ReadKey(true);
}
示例8: HandleDebuggerStopEvent
// Method to handle the Debugger DebuggerStop event.
// The debugger will remain in debugger stop mode until this event
// handler returns, at which time DebuggerStopEventArgs.ResumeAction should
// be set to indicate how the debugger should proceed (Continue, StepInto,
// StepOut, StepOver, Stop).
// This handler should run a REPL (Read Evaluate Print Loop) to allow user
// to investigate the state of script execution, by processing user commands
// with the Debugger.ProcessCommand method. If a user command releases the
// debugger then the DebuggerStopEventArgs.ResumeAction is set and this
// handler returns.
private void HandleDebuggerStopEvent(object sender, DebuggerStopEventArgs args)
{
Debugger debugger = sender as Debugger;
DebuggerResumeAction? resumeAction = null;
// Display messages pertaining to this debugger stop.
WriteDebuggerStopMessages(args);
// Simple REPL (Read Evaluate Print Loop) to process
// Debugger commands.
while (resumeAction == null)
{
// Write debug prompt.
Console.Write("[DBG] PS >> ");
string command = Console.ReadLine();
Console.WriteLine();
// Stream output from command processing to console.
var output = new PSDataCollection<PSObject>();
output.DataAdded += (dSender, dArgs) =>
{
foreach (var item in output.ReadAll())
{
Console.WriteLine(item);
}
};
// Process command.
// The Debugger.ProcesCommand method will parse and handle debugger specific
// commands such as 'h' (help), 'list', 'stepover', etc. If the command is
// not specific to the debugger then it will be evaluated as a PowerShell
// command or script. The returned DebuggerCommandResults object will indicate
// whether the command was evaluated by the debugger and if the debugger should
// be released with a specific resume action.
PSCommand psCommand = new PSCommand();
psCommand.AddScript(command).AddCommand("Out-String").AddParameter("Stream", true);
DebuggerCommandResults results = debugger.ProcessCommand(psCommand, output);
if (results.ResumeAction != null)
{
resumeAction = results.ResumeAction;
}
}
// Return from event handler with user resume action.
args.ResumeAction = resumeAction.Value;
}