public async void RunScript_ReadsDataFromInputStream() { var lf = TestLoggerFactory.Create(); var script = @"$Input | ForEach { Write-Output $_ }"; var expected = new[] { 32, 120, 71, 89, 20 }; var input = new PSDataCollection <PSObject>(5); _ = Task.Run( () => { foreach (var num in expected) { input.Add(num); Thread.Sleep(num); } input.Complete(); } ); var result = await PwshRunner.RunScript(script, lf.CreateLogger("Test"), null, input); var actual = result.Select(o => (int)o.BaseObject).ToArray(); Assert.Equal(expected, actual); }
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; }
internal static PSDataCollection <object> Serialize(IEnumerable collection) { PSDataCollection <object> psdataCollection = new PSDataCollection <object>(); if (collection != null) { foreach (object obj in collection) { if (MonadCommand.CanSerialize(obj)) { psdataCollection.Add(MonadCommand.Serialize(obj)); } else if (obj is Enum) { psdataCollection.Add(obj.ToString()); } else { psdataCollection.Add(obj); } } } psdataCollection.Complete(); return(psdataCollection); }
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); }
/// <summary> /// Invokes a PowerShell script block. /// </summary> /// <param name="script">A script to be invoked.</param> /// <param name="powerShell">PowerShell instance.</param> /// <param name="errorAction">Error callback function.</param> /// <returns></returns> internal static ICollection <PSObject> CallPowerShellScript( string script, System.Management.Automation.PowerShell powerShell, EventHandler <DataAddedEventArgs> errorAction) { try { powerShell.Clear(); var input = new PSDataCollection <PSObject>(); input.Complete(); var output = new PSDataCollection <PSObject>(); output.DataAdded += output_DataAdded; if (errorAction != null) { powerShell.Streams.Error.DataAdded += errorAction; } powerShell.AddScript(script); powerShell.Invoke(null, output, new PSInvocationSettings()); return(output.Count == 0 ? null : output); } finally { powerShell.Streams.Error.DataAdded -= errorAction; } }
public void TestDebugOutput() { using (var ps = PowerShell.Create()) { using (var rs = RunspaceFactory.CreateRunspace(_iss)) { rs.Open(); ps.Runspace = rs; ps.AddScript("$DebugPreference=[System.Management.Automation.ActionPreference]::Continue", false).Invoke(); ps.Commands.Clear(); ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("Write-Debug $_")) .AddParameter("ThrottleLimit", 1); var input = new PSDataCollection <int> { 1, 2, 3, 4, 5 }; input.Complete(); ps.Invoke <int>(input); Assert.IsFalse(ps.HadErrors, "We don't expect errors here"); var dbg = ps.Streams.Debug.ReadAll(); Assert.IsTrue(dbg.Any(d => d.Message == "1"), "Some debug message should be '1'"); } } }
private void HandleRunspaceAvailabilityChanged(object sender, RunspaceAvailabilityEventArgs e) { // Ignore nested commands. LocalRunspace localRunspace = sender as LocalRunspace; if (localRunspace != null) { var basePowerShell = localRunspace.GetCurrentBasePowerShell(); if ((basePowerShell != null) && (basePowerShell.IsNested)) { return; } } RunspaceAvailability prevAvailability = _previousRunspaceAvailability; _previousRunspaceAvailability = e.RunspaceAvailability; if ((e.RunspaceAvailability == RunspaceAvailability.Available) || (e.RunspaceAvailability == RunspaceAvailability.None)) { _debugBlockingCollection.Complete(); } else if ((e.RunspaceAvailability == RunspaceAvailability.Busy) && ((prevAvailability == RunspaceAvailability.Available) || (prevAvailability == RunspaceAvailability.None))) { _newRunningScriptEvent.Set(); } }
public string ExtractErrorFromErrorRecord(ErrorRecord record) { Pipeline pipeline = _runspace.CreatePipeline(command: "$input", addToHistory: false); pipeline.Commands.Add("out-string"); Collection <PSObject> result; using (var inputCollection = new PSDataCollection <object>()) { inputCollection.Add(record); inputCollection.Complete(); result = InvokeCore(pipeline, 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.TrimEnd(new[] { '\r', '\n' })); } } return(String.Empty); }
public void TestRecursiveFunctionCaptureOutput() { using (var ps = PowerShell.Create()) { ps.RunspacePool = m_runspacePool; ps.AddScript(@" function foo($x) {return 2 * $x} function bar($x) {return 3 * (foo $x)} ", false); ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("bar $_")) .AddParameter("ThrottleLimit", 1) .AddParameter("NoProgress"); var input = new PSDataCollection <int> { 1, 2, 3, 4, 5 }; input.Complete(); var output = ps.Invoke <int>(input); var sum = output.Aggregate(0, (a, b) => a + b); Assert.AreEqual(90, sum); } }
public PowerShellPoolMember(PowershellPool pool, int index) { m_pool = pool; m_index = index; m_poolStreams = m_pool.Streams; m_input.Complete(); CreatePowerShell(); }
public PowerShellPoolMember(PowershellPool pool, int index, InitialSessionState initialSessionState) { _pool = pool; _index = index; _initialSessionState = initialSessionState; _poolStreams = _pool.Streams; _input.Complete(); CreatePowerShell(initialSessionState); }
/// <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); }
private void HandleJobStateChangedEvent(object sender, JobStateEventArgs stateChangedArgs) { Job job = sender as Job; if (job.IsFinishedState(stateChangedArgs.JobStateInfo.State)) { _debugCollection.Complete(); } }
/// <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) { IContainsErrorRecord errorRecord = e as IContainsErrorRecord; object error = errorRecord != null ? errorRecord.ErrorRecord : new ErrorRecord(e, "Host.ReportException", ErrorCategory.NotSpecified, null); lock (_instanceLock) { _currentPowerShell = Shell.Create(); } _currentPowerShell.Runspace = Runspace; try { _currentPowerShell.AddScript("$input").AddCommand("out-string"); // Do not merge errors, this function will swallow errors. Collection <PSObject> result; PSDataCollection <object> inputCollection = new PSDataCollection <object> { error }; inputCollection.Complete(); lock (_executionLock) { result = _currentPowerShell.Invoke(inputCollection); } if (result.Count > 0) { string output = result[0].BaseObject as string; // Remove \r\n, which is added by the Out-String cmdlet. if (!string.IsNullOrEmpty(output)) { _powerShellHost.UI.WriteErrorLine(output.Substring(0, output.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 (_instanceLock) { _currentPowerShell.Dispose(); _currentPowerShell = null; } } } }
/// <inheritdoc /> protected override async Task <Result <Array <Entity>, IError> > Run( IStateMonad stateMonad, CancellationToken cancellationToken) { var script = await Script.Run(stateMonad, cancellationToken).Map(x => x.GetStringAsync()); if (script.IsFailure) { return(script.ConvertFailure <Array <Entity> >()); } Entity?vars = null; if (Variables != null) { var variables = await Variables.Run(stateMonad, cancellationToken); if (variables.IsFailure) { return(variables.ConvertFailure <Array <Entity> >()); } vars = variables.Value; } PSDataCollection <PSObject>?input = null; #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously async ValueTask <Result <Unit, IError> > AddObject(Entity x, CancellationToken ct) { input.Add(PwshRunner.PSObjectFromEntity(x)); return(Unit.Default); } #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously if (Input != null) { var inputStream = await Input.Run(stateMonad, cancellationToken); if (inputStream.IsFailure) { return(inputStream.ConvertFailure <Array <Entity> >()); } input = new PSDataCollection <PSObject>(); _ = inputStream.Value.ForEach(AddObject, cancellationToken) .ContinueWith(_ => input.Complete(), cancellationToken); } var stream = PwshRunner.GetEntityEnumerable(script.Value, stateMonad.Logger, vars, input) .ToSCLArray(); return(stream); }
/// <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; } } } }
/// <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); }
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"); 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)) { this.myHost.UI.WriteErrorLine(str.Substring(0, str.Length - 2)); } } } finally { lock (this.instanceLock) { this.currentPowerShell.Dispose(); this.currentPowerShell = null; } } } }
/// <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) { return; } var icer = e as IContainsErrorRecord; object error = icer != null ? icer.ErrorRecord : new ErrorRecord(e, "Host.ReportException", ErrorCategory.NotSpecified, null); lock (_instanceLock) { _currentPowerShell = PowerShell.Create(); } _currentPowerShell.Runspace = _runspace; try { _currentPowerShell.AddScript("$input").AddCommand("out-string"); // Do not merge errors, this function will swallow errors. var inputCollection = new PSDataCollection <object> { error }; inputCollection.Complete(); var result = _currentPowerShell.Invoke(inputCollection); if (result.Count > 0) { var str = result[0].BaseObject as string; if (!string.IsNullOrEmpty(str)) { // Remove \r\n, which is added by the Out-String cmdlet. _host.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 (_instanceLock) { _currentPowerShell.Dispose(); _currentPowerShell = null; } } }
private void InvokeAsyncIfPossible() { var output = NewOutputCollection(); Task.Factory.StartNew(() => { var input = new PSDataCollection <object>(); input.Complete(); var asyncResult = _powershell.BeginInvoke(input, output); _powershell.EndInvoke(asyncResult); _result.Completed(); }, TaskCreationOptions.LongRunning); }
/// <summary> /// Return the last output to the user. This will be null if the operation did not succeed. /// outputAction is the action that will be performed whenever an object is outputted to the powershell pipeline /// </summary> /// <typeparam name="T"></typeparam> /// <param name="powershell"></param> /// <param name="command"></param> /// <param name="outputAction"></param> /// <param name="errorAction"></param> /// <param name="args"></param> /// <returns></returns> internal static T InvokeFunction <T>(this PowerShell powershell, string command, EventHandler <DataAddedEventArgs> outputAction, EventHandler <DataAddedEventArgs> errorAction, params object[] args) { if (powershell != null) { powershell.Clear().AddCommand(command); foreach (var arg in args) { powershell.AddArgument(arg); } #if DEBUG NativeMethods.OutputDebugString("[Cmdlet:debugging] -- InvokeFunction ({0}, {1})".format(command, args.Select(each => (each ?? "<NULL>").ToString()).JoinWithComma(), powershell.InvocationStateInfo.Reason)); #endif var input = new PSDataCollection <PSObject>(); input.Complete(); var output = new PSDataCollection <PSObject>(); if (outputAction != null) { output.DataAdded += outputAction; } if (errorAction != null) { powershell.Streams.Error.DataAdded += errorAction; } powershell.Invoke(null, output, new PSInvocationSettings()); if (output.Count == 0) { return(default(T)); } // return the last output to the user PSObject last = output.Last(); if (last != null) { // convert last to T return((T)last.ImmediateBaseObject); } } return(default(T)); }
public void TestParallelOutput() { using (var ps = PowerShell.Create()) { //ps.RunspacePool = m_runspacePool; ps.AddCommand("Invoke-Parallel") .AddParameter("ScriptBlock", ScriptBlock.Create("$_* 2")) .AddParameter("ThrottleLimit", 10); var input = new PSDataCollection <int>(Enumerable.Range(1, 1000)); input.Complete(); var output = ps.Invoke <int>(input); var sum = output.Aggregate(0, (a, b) => a + b); Assert.AreEqual(1001000, sum); } }
/// <summary> /// Dispose /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { if (disposing) { if (_ps.InvocationStateInfo.State == PSInvocationState.Running) { _ps.Stop(); } _ps.Dispose(); _input.Complete(); _output.Complete(); } base.Dispose(disposing); }
/// <summary> /// Default constructor. /// </summary> public PowerShellStreams(PSDataCollection <TInput> pipelineInput) { // Populate the input collection if there is any... _inputStream = pipelineInput ?? new PSDataCollection <TInput>(); _inputStream.Complete(); _outputStream = new PSDataCollection <TOutput>(); _errorStream = new PSDataCollection <ErrorRecord>(); _warningStream = new PSDataCollection <WarningRecord>(); _progressStream = new PSDataCollection <ProgressRecord>(); _verboseStream = new PSDataCollection <VerboseRecord>(); _debugStream = new PSDataCollection <DebugRecord>(); _informationStream = new PSDataCollection <InformationRecord>(); _disposed = false; }
/// <summary> /// Stop processing. /// </summary> protected override void StopProcessing() { // Cancel job debugging. Debugger debugger = _debugger; if ((debugger != null) && (_job != null)) { debugger.StopDebugJob(_job); } // Unblock the data collection. PSDataCollection <PSStreamObject> debugCollection = _debugCollection; if (debugCollection != null) { debugCollection.Complete(); } }
/// <summary> /// Marking all the streams as completed so that no further data can be added and /// jobs will know that there is no more data coming in. /// </summary> public void CloseAll() { if (!_disposed) { lock (_syncLock) { if (!_disposed) { _outputStream.Complete(); _errorStream.Complete(); _warningStream.Complete(); _progressStream.Complete(); _verboseStream.Complete(); _debugStream.Complete(); _informationStream.Complete(); } } } }
public void TestNoDebugOutputWithoutPreference() { using (var ps = PowerShell.Create()) { ps.RunspacePool = m_runspacePool; ps.Commands.Clear(); ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("Write-Debug $_")) .AddParameter("ThrottleLimit", 1); var input = new PSDataCollection <int> { 1, 2, 3, 4, 5 }; input.Complete(); ps.Invoke <int>(input); var dbg = ps.Streams.Debug.ReadAll(); Assert.IsFalse(dbg.Any(d => d.Message == "1"), "No debug message should be '1'"); } }
public void TestNoVerboseOutputWithoutPreference() { using (var ps = PowerShell.Create()) { ps.RunspacePool = m_runspacePool; ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("Write-Verbose $_")) .AddParameter("ThrottleLimit", 1); var input = new PSDataCollection <int> { 1, 2, 3, 4, 5 }; input.Complete(); ps.Invoke <int>(input); Assert.IsFalse(ps.HadErrors, "We don't expect errors here"); var vrb = ps.Streams.Verbose.ReadAll(); Assert.IsFalse(vrb.Any(v => v.Message == "1"), "No verbose message should be '1'"); } }
public void TestNoErrorOutputWithoutPreference() { using (var ps = PowerShell.Create()) { ps.RunspacePool = m_runspacePool; ps.AddScript("$ErrorActionPreference='SilentlyContinue'", false).Invoke(); ps.Commands.Clear(); ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("Write-Error -message $_ -TargetObject $_")) .AddParameter("ThrottleLimit", 1); var input = new PSDataCollection <int> { 1, 2, 3, 4, 5 }; input.Complete(); ps.Invoke <int>(input); var err = ps.Streams.Error.ReadAll(); Assert.IsFalse(err.Any(e => e.Exception.Message == "1"), "No Error message should be '1'"); } }
public void TestNoWarningOutputWithoutPreference() { using (var ps = PowerShell.Create()) { ps.RunspacePool = m_runspacePool; ps.AddScript("$WarningPreference='SilentlyContinue'", false).Invoke(); ps.Commands.Clear(); ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("Write-Warning $_")) .AddParameter("ThrottleLimit", 1); var input = new PSDataCollection <int> { 1, 2, 3, 4, 5 }; input.Complete(); ps.Invoke <int>(input); var wrn = ps.Streams.Warning.ReadAll(); Assert.IsFalse(wrn.Any(w => w.Message == "1"), "No warning message should be '1'"); } }
/// <summary> /// Dispose /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _input.Complete(); _output.Complete(); if (_ps != null) { _ps.Dispose(); _ps = null; } if (_rs != null) { _rs.Dispose(); _rs = null; } } }
private void ReportException(Exception e) { object error; if (e is IContainsErrorRecord) { error = (e as IContainsErrorRecord).ErrorRecord; } else { error = new ErrorRecord(e, "Host.ReportException", ErrorCategory.NotSpecified, null); } try { using (var ps = _host.CreatePowerShell()) { ps.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 = ps.Invoke(inputCollection); if (result.Any()) { var str = result.First().BaseObject as string; if (!string.IsNullOrEmpty(str)) { _host.UI.WriteErrorLine(str.Substring(0, str.Length - 2)); } } } } catch (Exception ex) // exception reporting might fail, depends on runspace state - just ignore any exception { logger.Error(ex); } }
/// <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) return; var icer = e as IContainsErrorRecord; object error = icer != null ? icer.ErrorRecord : new ErrorRecord(e, "Host.ReportException", ErrorCategory.NotSpecified, null); lock (_instanceLock) { _currentPowerShell = PowerShell.Create(); } _currentPowerShell.Runspace = _runspace; try { _currentPowerShell.AddScript("$input").AddCommand("out-string"); // Do not merge errors, this function will swallow errors. var inputCollection = new PSDataCollection<object> {error}; inputCollection.Complete(); var result = _currentPowerShell.Invoke(inputCollection); if (result.Count > 0) { var str = result[0].BaseObject as string; if (!string.IsNullOrEmpty(str)) { // Remove \r\n, which is added by the Out-String cmdlet. _host.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 (_instanceLock) { _currentPowerShell.Dispose(); _currentPowerShell = null; } } }
internal static void ContinueCommand(RemoteRunspace remoteRunspace, Pipeline cmd, PSHost host, bool inDebugMode, System.Management.Automation.ExecutionContext context) { RemotePipeline remotePipeline = cmd as RemotePipeline; if (remotePipeline != null) { using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) { PSInvocationSettings settings = new PSInvocationSettings() { Host = host }; PSDataCollection<PSObject> input = new PSDataCollection<PSObject>(); CommandInfo commandInfo = new CmdletInfo("Out-Default", typeof(OutDefaultCommand), null, null, context); Command outDefaultCommand = new Command(commandInfo); ps.AddCommand(outDefaultCommand); IAsyncResult async = ps.BeginInvoke<PSObject>(input, settings, null, null); RemoteDebugger remoteDebugger = remoteRunspace.Debugger as RemoteDebugger; if (remoteDebugger != null) { // Update client with breakpoint information from pushed runspace. // Information will be passed to the client via the Debugger.BreakpointUpdated event. remoteDebugger.SendBreakpointUpdatedEvents(); if (!inDebugMode) { // Enter debug mode if remote runspace is in debug stop mode. remoteDebugger.CheckStateAndRaiseStopEvent(); } } // Wait for debugged cmd to complete. while (!remotePipeline.Output.EndOfPipeline) { remotePipeline.Output.WaitHandle.WaitOne(); while (remotePipeline.Output.Count > 0) { input.Add(remotePipeline.Output.Read()); } } input.Complete(); ps.EndInvoke(async); } } }
public void TestNoDebugOutputWithoutPreference() { using (var ps = PowerShell.Create()) { ps.RunspacePool = m_runspacePool; ps.Commands.Clear(); ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("Write-Debug $_")) .AddParameter("ThrottleLimit", 1); var input = new PSDataCollection<int> {1, 2, 3, 4, 5}; input.Complete(); ps.Invoke<int>(input); var dbg = ps.Streams.Debug.ReadAll(); Assert.IsFalse(dbg.Any(d => d.Message == "1"), "No debug message should be '1'"); } }
private DebuggerCommandResults ProcessDebugCommand(string cmd, out Exception e) { DebuggerCommandResults results = null; try { _parent.DebuggerCanStopCommand = true; // Use PowerShell object to write streaming data to host. using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) { PSInvocationSettings settings = new PSInvocationSettings() { Host = _parent }; PSDataCollection<PSObject> output = new PSDataCollection<PSObject>(); ps.AddCommand("Out-Default"); IAsyncResult async = ps.BeginInvoke<PSObject>(output, settings, null, null); // Let debugger evaluate command and stream output data. results = _parent.Runspace.Debugger.ProcessCommand( new PSCommand( new Command(cmd, true)), output); output.Complete(); ps.EndInvoke(async); } e = null; } catch (Exception ex) { ConsoleHost.CheckForSevereException(ex); e = ex; results = new DebuggerCommandResults(null, false); } finally { _parent.DebuggerCanStopCommand = false; } // Exit debugger if command fails to evaluate. return results ?? new DebuggerCommandResults(DebuggerResumeAction.Continue, false); }
public void TestDebugOutput() { using (var ps = PowerShell.Create()) { using (var rs = RunspaceFactory.CreateRunspace(_iss)) { rs.Open(); ps.Runspace = rs; ps.AddScript("$DebugPreference=[System.Management.Automation.ActionPreference]::Continue", false).Invoke(); ps.Commands.Clear(); ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("Write-Debug $_")) .AddParameter("ThrottleLimit", 1); var input = new PSDataCollection<int> { 1, 2, 3, 4, 5 }; input.Complete(); ps.Invoke<int>(input); Assert.IsFalse(ps.HadErrors, "We don't expect errors here"); var dbg = ps.Streams.Debug.ReadAll(); Assert.IsTrue(dbg.Any(d => d.Message == "1"), "Some debug message should be '1'"); } } }
public void TestNoErrorOutputWithoutPreference() { using (var ps = PowerShell.Create()) { ps.RunspacePool = m_runspacePool; ps.AddScript("$ErrorActionPreference='SilentlyContinue'", false).Invoke(); ps.Commands.Clear(); ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("Write-Error -message $_ -TargetObject $_")) .AddParameter("ThrottleLimit", 1); var input = new PSDataCollection<int> {1, 2, 3, 4, 5}; input.Complete(); ps.Invoke<int>(input); var err = ps.Streams.Error.ReadAll(); Assert.IsFalse(err.Any(e => e.Exception.Message == "1"), "No Error message should be '1'"); } }
public void TestParallelOutput() { using (var ps = PowerShell.Create()) { //ps.RunspacePool = m_runspacePool; ps.AddCommand("Invoke-Parallel") .AddParameter("ScriptBlock", ScriptBlock.Create("$_* 2")) .AddParameter("ThrottleLimit", 10); var input = new PSDataCollection<int>(Enumerable.Range(1, 1000)); input.Complete(); var output = ps.Invoke<int>(input); var sum = output.Aggregate(0, (a, b) => a + b); Assert.AreEqual(1001000, sum); } }
public void TestNoVerboseOutputWithoutPreference() { using (var ps = PowerShell.Create()) { ps.Runspace = RunspaceFactory.CreateRunspace(); ps.Runspace.Open(); ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("Write-Verbose $_")) .AddParameter("ThrottleLimit", 1); var input = new PSDataCollection<int> {1, 2, 3, 4, 5}; input.Complete(); ps.Invoke<int>(input); Assert.IsFalse(ps.HadErrors, "We don't expect errors here"); var vrb = ps.Streams.Verbose.ReadAll(); Assert.IsFalse(vrb.Any(v => v.Message == "1"), "No verbose message should be '1'"); ps.Runspace.Dispose(); } }
public string ExtractErrorFromErrorRecord(ErrorRecord record) { Pipeline pipeline = _runspace.CreatePipeline(command: "$input", addToHistory: false); pipeline.Commands.Add("out-string"); Collection<PSObject> result; using (var inputCollection = new PSDataCollection<object>()) { inputCollection.Add(record); inputCollection.Complete(); result = InvokeCore(pipeline, 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.TrimEnd(new[] { '\r', '\n' }); } } return String.Empty; }
public void TestProgressOutput2Workers() { using (var ps = PowerShell.Create()) { ps.RunspacePool = m_runspacePool; ps.AddScript("$ProgressPreference='Continue'", false).Invoke(); ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("Write-Progress -activity 'Test' -Status 'Status' -currentoperation $_")) .AddParameter("ThrottleLimit", 2); var input = new PSDataCollection<int> { 1, 2, 3, 4, 5, 6, 7,8, 9,10 }; input.Complete(); ps.Invoke(input); var progress = ps.Streams.Progress.ReadAll(); Assert.IsTrue(19 <= progress.Count(pr => pr.Activity == "Invoke-Parallel" || pr.Activity == "Test")); } }
public void TestRecursiveFunctionCaptureOutput() { using (var ps = PowerShell.Create()) { ps.RunspacePool = m_runspacePool; ps.AddScript(@" function foo($x) {return 2 * $x} function bar($x) {return 3 * (foo $x)} ", false); ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("bar $_")) .AddParameter("ThrottleLimit", 1) .AddParameter("NoProgress"); var input = new PSDataCollection<int> {1, 2, 3, 4, 5}; input.Complete(); var output = ps.Invoke<int>(input); var sum = output.Aggregate(0, (a, b) => a + b); Assert.AreEqual(90, sum); } }
public void TestVerboseOutput() { using (var ps = PowerShell.Create()) { ps.RunspacePool = m_runspacePool; ps.AddScript("$VerbosePreference=[System.Management.Automation.ActionPreference]::Continue", false).Invoke(); ps.Commands.Clear(); ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("Write-Verbose $_")) .AddParameter("ThrottleLimit", 1); var input = new PSDataCollection<int> {1, 2, 3, 4, 5}; input.Complete(); ps.Invoke<int>(input); Assert.IsFalse(ps.HadErrors, "We don't expect errors here"); var vrb = ps.Streams.Verbose.ReadAll(); Assert.IsTrue(vrb.Any(v => v.Message == "1"), "Some verbose message should be '1'"); } }
public void TestWarningOutput() { using (var ps = PowerShell.Create()) { ps.RunspacePool = m_runspacePool; ps.AddScript("$WarningPreference='Continue'", false).Invoke(); ps.Commands.Clear(); ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("Write-Warning $_")) .AddParameter("ThrottleLimit", 1); var input = new PSDataCollection<int> {1, 2, 3, 4, 5}; input.Complete(); ps.Invoke<int>(input); var wrn = ps.Streams.Warning.ReadAll(); Assert.IsTrue(wrn.Any(w => w.Message == "1"), "Some warning message should be '1'"); } }
/// <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) { return; } var icer = e as IContainsErrorRecord; object error = icer != null ? icer.ErrorRecord : new ErrorRecord(e, "Host.ReportException", ErrorCategory.NotSpecified, null); using (var powerShell = PowerShell.Create()) { powerShell.Runspace = _runspace; powerShell.AddScript("$input").AddCommand("out-string"); // Do not merge errors, this function will swallow errors. var inputCollection = new PSDataCollection<object> {error}; inputCollection.Complete(); var result = powerShell.Invoke(inputCollection); if (result.Count > 0) { var str = result[0].BaseObject as string; if (!string.IsNullOrEmpty(str)) { // Remove \r\n, which is added by the Out-String cmdlet. _psRemoteHost.UI.WriteErrorLine(str.Substring(0, str.Length - 2)); } } } }
public void TestNoProgressOutput() { using (var ps = PowerShell.Create()) { ps.RunspacePool = m_runspacePool; ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("Write-Progress -activity 'Test' -Status 'Status' -currentoperation $_")) .AddParameter("ThrottleLimit", 1) .AddParameter("NoProgress"); var input = new PSDataCollection<int> {1, 2, 3, 4, 5}; input.Complete(); ps.Invoke(input); var progress = ps.Streams.Progress.ReadAll(); Assert.IsFalse(progress.Any(pr => pr.Activity == "Invoke-Parallel")); Assert.AreEqual(5, progress.Count(pr => pr.Activity == "Test")); } }
/// <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; } } } }
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"); 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)) { this.myHost.UI.WriteErrorLine(str.Substring(0, str.Length - 2)); } } } finally { lock (this.instanceLock) { this.currentPowerShell.Dispose(); this.currentPowerShell = null; } } } }