private PSDataCollection <PSObject> InvokePowerShell(PowerShell powershell, RunspaceCreatedEventArgs args) { string str; HostInfo hostInfo = this.remoteHost.HostInfo; IAsyncResult asyncResult = new ServerPowerShellDriver(powershell, null, true, Guid.Empty, this.InstanceId, this, args.Runspace.ApartmentState, hostInfo, RemoteStreamOptions.AddInvocationInfo, false, args.Runspace).Start(); PSDataCollection <PSObject> datas = powershell.EndInvoke(asyncResult); ArrayList dollarErrorVariable = (ArrayList)powershell.Runspace.GetExecutionContext.DollarErrorVariable; if (dollarErrorVariable.Count <= 0) { return(datas); } ErrorRecord record = dollarErrorVariable[0] as ErrorRecord; if (record != null) { str = record.ToString(); } else { Exception exception = dollarErrorVariable[0] as Exception; if (exception != null) { str = (exception.Message != null) ? exception.Message : string.Empty; } else { str = string.Empty; } } throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings", PSRemotingErrorId.StartupScriptThrewTerminatingError.ToString(), new object[] { str }); }
private void HandleCreateAndInvokePowerShell(object sender, RemoteDataEventArgs <RemoteDataObject <PSObject> > eventArgs) { RemoteDataObject <PSObject> data = eventArgs.Data; HostInfo hostInfo = RemotingDecoder.GetHostInfo(data.Data); ApartmentState apartmentState = RemotingDecoder.GetApartmentState(data.Data); RemoteStreamOptions remoteStreamOptions = RemotingDecoder.GetRemoteStreamOptions(data.Data); PowerShell powerShell = RemotingDecoder.GetPowerShell(data.Data); bool noInput = RemotingDecoder.GetNoInput(data.Data); bool addToHistory = RemotingDecoder.GetAddToHistory(data.Data); bool isNested = false; if (this.serverCapability.ProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM) { isNested = RemotingDecoder.GetIsNested(data.Data); } if (isNested) { if (this.dsHandler.GetAssociatedPowerShellDataStructureHandler(powerShell.InstanceId) != null) { throw new InvalidOperationException("NestedPipeline is not supported in this release."); } powerShell.SetIsNested(false); if ((this.localRunspacePool.GetMaxRunspaces() == 1) && (this.dsHandler.GetPowerShellDataStructureHandler() != null)) { new ServerSteppablePipelineDriver(powerShell, noInput, data.PowerShellId, data.RunspacePoolId, this, apartmentState, hostInfo, remoteStreamOptions, addToHistory, this.rsToUseForSteppablePipeline, this.eventSubscriber, this.inputCollection).Start(); return; } } ServerPowerShellDriver driver2 = new ServerPowerShellDriver(powerShell, null, noInput, data.PowerShellId, data.RunspacePoolId, this, apartmentState, hostInfo, remoteStreamOptions, addToHistory, null); this.inputCollection = driver2.InputCollection; driver2.Start(); }
internal ServerPowerShellDataStructureHandler( ServerPowerShellDriver driver, AbstractServerTransportManager transportManager) { using (ServerPowerShellDataStructureHandler.tracer.TraceConstructor((object)this)) { this.clientPowerShellId = driver.InstanceId; this.clientRunspacePoolId = driver.RunspacePoolId; this.transportManager = transportManager; this.streamSerializationOptions = driver.RemoteStreamOptions; transportManager.Closing += new EventHandler(this.HandleTransportClosing); } }
internal ServerPowerShellDataStructureHandler CreatePowerShellDataStructureHandler( ServerPowerShellDriver driver) { using (ServerRunspacePoolDataStructureHandler.tracer.TraceMethod()) { AbstractServerTransportManager transportManager = (AbstractServerTransportManager)this.transportManager; if (driver.InstanceId != Guid.Empty) { transportManager = this.transportManager.GetCommandTransportManager(driver.InstanceId); } ServerPowerShellDataStructureHandler structureHandler = new ServerPowerShellDataStructureHandler(driver, transportManager); lock (this.associationSyncObject) this.associatedShells.Add(structureHandler.PowerShellId, structureHandler); structureHandler.RemoveAssociation += new EventHandler(this.HandleRemoveAssociation); return(structureHandler); } }
/// <summary> /// Handle the invocation of powershell /// </summary> /// <param name="sender">sender of this event, unused</param> /// <param name="eventArgs">arguments describing this event</param> private void HandleCreateAndInvokePowerShell(object sender, RemoteDataEventArgs<RemoteDataObject<PSObject>> eventArgs) { RemoteDataObject<PSObject> data = eventArgs.Data; // it is sufficient to just construct the powershell // driver, the local powershell on server side is // invoked from within the driver HostInfo hostInfo = RemotingDecoder.GetHostInfo(data.Data); #if !CORECLR // No ApartmentState In CoreCLR ApartmentState apartmentState = RemotingDecoder.GetApartmentState(data.Data); #endif RemoteStreamOptions streamOptions = RemotingDecoder.GetRemoteStreamOptions(data.Data); PowerShell powershell = RemotingDecoder.GetPowerShell(data.Data); bool noInput = RemotingDecoder.GetNoInput(data.Data); bool addToHistory = RemotingDecoder.GetAddToHistory(data.Data); bool isNested = false; // The server would've dropped the protocol version of an older client was connecting if (_serverCapability.ProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM) { isNested = RemotingDecoder.GetIsNested(data.Data); } // Perform pre-processing of command for over the wire debugging commands. if (_serverRemoteDebugger != null) { DebuggerCommandArgument commandArgument; bool terminateImmediate = false; var result = PreProcessDebuggerCommand(powershell.Commands, _serverRemoteDebugger.IsActive, _serverRemoteDebugger.IsRemote, out commandArgument); switch (result) { case PreProcessCommandResult.SetDebuggerAction: // Run this directly on the debugger and terminate the remote command. _serverRemoteDebugger.SetDebuggerAction(commandArgument.ResumeAction.Value); terminateImmediate = true; break; case PreProcessCommandResult.SetDebugMode: // Set debug mode directly and terminate remote command. _serverRemoteDebugger.SetDebugMode(commandArgument.Mode.Value); terminateImmediate = true; break; case PreProcessCommandResult.SetDebuggerStepMode: // Enable debugger and set to step action, then terminate remote command. _serverRemoteDebugger.SetDebuggerStepMode(commandArgument.DebuggerStepEnabled.Value); terminateImmediate = true; break; case PreProcessCommandResult.SetPreserveUnhandledBreakpointMode: _serverRemoteDebugger.UnhandledBreakpointMode = commandArgument.UnhandledBreakpointMode.Value; terminateImmediate = true; break; case PreProcessCommandResult.ValidNotProcessed: terminateImmediate = true; break; } // If we don't want to run or queue a command to run in the server session then // terminate the command here by making it a No Op. if (terminateImmediate) { ServerPowerShellDriver noOpDriver = new ServerPowerShellDriver( powershell, null, noInput, data.PowerShellId, data.RunspacePoolId, this, #if !CORECLR // No ApartmentState In CoreCLR apartmentState, #endif hostInfo, streamOptions, addToHistory, null); noOpDriver.RunNoOpCommand(); return; } } if (_remoteHost.IsRunspacePushed) { // If we have a pushed runspace then execute there. // Ensure debugger is enabled to the original mode it was set to. if (_serverRemoteDebugger != null) { _serverRemoteDebugger.CheckDebuggerState(); } StartPowerShellCommandOnPushedRunspace( powershell, null, data.PowerShellId, data.RunspacePoolId, hostInfo, streamOptions, noInput, addToHistory); return; } else if (isNested) { if (RunspacePool.GetMaxRunspaces() == 1) { if (_driverNestedInvoker != null && _driverNestedInvoker.IsActive) { if (_driverNestedInvoker.IsAvailable == false) { // A nested command is already running. throw new PSInvalidOperationException( StringUtil.Format(RemotingErrorIdStrings.CannotInvokeNestedCommandNestedCommandRunning)); } // Handle as nested pipeline invocation. powershell.SetIsNested(true); // Always invoke PowerShell commands on pipeline worker thread // for single runspace case, to support nested invocation requests (debugging scenario). ServerPowerShellDriver srdriver = new ServerPowerShellDriver( powershell, null, noInput, data.PowerShellId, data.RunspacePoolId, this, #if !CORECLR // No ApartmentState In CoreCLR apartmentState, #endif hostInfo, streamOptions, addToHistory, _rsToUseForSteppablePipeline); _inputCollection = srdriver.InputCollection; _driverNestedInvoker.InvokeDriverAsync(srdriver); return; } else if (_serverRemoteDebugger != null && _serverRemoteDebugger.InBreakpoint && _serverRemoteDebugger.IsPushed) { _serverRemoteDebugger.StartPowerShellCommand( powershell, data.PowerShellId, data.RunspacePoolId, this, #if !CORECLR // No ApartmentState In CoreCLR apartmentState, #endif _remoteHost, hostInfo, streamOptions, addToHistory); return; } else if (powershell.Commands.Commands.Count == 1 && !powershell.Commands.Commands[0].IsScript && ((powershell.Commands.Commands[0].CommandText.IndexOf("Get-PSDebuggerStopArgs", StringComparison.OrdinalIgnoreCase) != -1) || (powershell.Commands.Commands[0].CommandText.IndexOf("Set-PSDebuggerAction", StringComparison.OrdinalIgnoreCase) != -1))) { // We do not want to invoke debugger commands in the steppable pipeline. // Consider adding IsSteppable message to PSRP to handle this. // This will be caught on the client. throw new PSInvalidOperationException(); } ServerPowerShellDataStructureHandler psHandler = DataStructureHandler.GetPowerShellDataStructureHandler(); if (psHandler != null) { // Have steppable invocation request. powershell.SetIsNested(false); // Execute command concurrently ServerSteppablePipelineDriver spDriver = new ServerSteppablePipelineDriver( powershell, noInput, data.PowerShellId, data.RunspacePoolId, this, #if !CORECLR // No ApartmentState In CoreCLR apartmentState, #endif hostInfo, streamOptions, addToHistory, _rsToUseForSteppablePipeline, _eventSubscriber, _inputCollection); spDriver.Start(); return; } } // Allow command to run as non-nested and non-stepping. powershell.SetIsNested(false); } // Invoke command normally. Ensure debugger is enabled to the // original mode it was set to. if (_serverRemoteDebugger != null) { _serverRemoteDebugger.CheckDebuggerState(); } // Invoke PowerShell on driver runspace pool. ServerPowerShellDriver driver = new ServerPowerShellDriver( powershell, null, noInput, data.PowerShellId, data.RunspacePoolId, this, #if !CORECLR // No ApartmentState In CoreCLR apartmentState, #endif hostInfo, streamOptions, addToHistory, null); _inputCollection = driver.InputCollection; driver.Start(); }
/// <summary> /// Invokes a PowerShell instance /// </summary> /// <param name="powershell"></param> /// <param name="args"></param> /// <returns></returns> private PSDataCollection<PSObject> InvokePowerShell(PowerShell powershell, RunspaceCreatedEventArgs args) { Debug.Assert(powershell != null, "powershell shouldn't be null"); // run the startup script on the runspace's host HostInfo hostInfo = _remoteHost.HostInfo; ServerPowerShellDriver driver = new ServerPowerShellDriver( powershell, null, true, Guid.Empty, this.InstanceId, this, #if !CORECLR // No ApartmentState In CoreCLR args.Runspace.ApartmentState, #endif hostInfo, RemoteStreamOptions.AddInvocationInfo, false, args.Runspace); IAsyncResult asyncResult = driver.Start(); // if there was an exception running the script..this may throw..this will // result in the runspace getting closed/broken. PSDataCollection<PSObject> results = powershell.EndInvoke(asyncResult); // find out if there are any error records reported. If there is one, report the error.. // this will result in the runspace getting closed/broken. ArrayList errorList = (ArrayList)powershell.Runspace.GetExecutionContext.DollarErrorVariable; if (errorList.Count > 0) { string exceptionThrown; ErrorRecord lastErrorRecord = errorList[0] as ErrorRecord; if (lastErrorRecord != null) { exceptionThrown = lastErrorRecord.ToString(); } else { Exception lastException = errorList[0] as Exception; if (lastException != null) { exceptionThrown = (lastException.Message != null) ? lastException.Message : string.Empty; } else { exceptionThrown = string.Empty; } } throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.StartupScriptThrewTerminatingError, exceptionThrown); } return results; }
internal void StartPowerShellCommand( PowerShell powershell, Guid powershellId, Guid runspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, #if !CORECLR // No ApartmentState In CoreCLR ApartmentState apartmentState, #endif ServerRemoteHost remoteHost, HostInfo hostInfo, RemoteStreamOptions streamOptions, bool addToHistory) { // For nested debugger command processing, invoke command on new local runspace since // the root script debugger runspace is unavailable (it is running a PS script or a // workflow function script). Runspace runspace = (remoteHost != null) ? RunspaceFactory.CreateRunspace(remoteHost) : RunspaceFactory.CreateRunspace(); runspace.Open(); try { powershell.InvocationStateChanged += HandlePowerShellInvocationStateChanged; powershell.SetIsNested(false); string script = @" param ($Debugger, $Commands, $output) trap { throw $_ } $Debugger.ProcessCommand($Commands, $output) "; PSDataCollection<PSObject> output = new PSDataCollection<PSObject>(); PSCommand Commands = new PSCommand(powershell.Commands); powershell.Commands.Clear(); powershell.AddScript(script).AddParameter("Debugger", this).AddParameter("Commands", Commands).AddParameter("output", output); ServerPowerShellDriver driver = new ServerPowerShellDriver( powershell, null, true, powershellId, runspacePoolId, runspacePoolDriver, #if !CORECLR // No ApartmentState In CoreCLR apartmentState, #endif hostInfo, streamOptions, addToHistory, runspace, output); driver.Start(); } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); runspace.Close(); runspace.Dispose(); } }
public void Dispatch(ServerPowerShellDriver driver) { CheckDisposed(); lock (_syncObject) { _driverInvokeQueue.Enqueue(driver); _processDrivers.Set(); } }
/// <summary> /// Submit a driver object to be invoked. /// </summary> /// <param name="driver">ServerPowerShellDriver</param> public void InvokeDriverAsync(ServerPowerShellDriver driver) { InvokePump currentPump; if (!_invokePumpStack.TryPeek(out currentPump)) { throw new PSInvalidOperationException(RemotingErrorIdStrings.PowerShellInvokerInvalidState); } currentPump.Dispatch(driver); }
/// <summary> /// Starts the PowerShell command on the currently pushed Runspace /// </summary> /// <param name="powershell">PowerShell command or script</param> /// <param name="extraPowerShell">PowerShell command to run after first completes</param> /// <param name="powershellId">PowerShell Id</param> /// <param name="runspacePoolId">RunspacePool Id</param> /// <param name="hostInfo">Host Info</param> /// <param name="streamOptions">Remote stream options</param> /// <param name="noInput">False when input is provided</param> /// <param name="addToHistory">Add to history</param> private void StartPowerShellCommandOnPushedRunspace( PowerShell powershell, PowerShell extraPowerShell, Guid powershellId, Guid runspacePoolId, HostInfo hostInfo, RemoteStreamOptions streamOptions, bool noInput, bool addToHistory) { Runspace runspace = _remoteHost.PushedRunspace; ServerPowerShellDriver driver = new ServerPowerShellDriver( powershell, extraPowerShell, noInput, powershellId, runspacePoolId, this, #if !CORECLR // No ApartmentState In CoreCLR ApartmentState.MTA, #endif hostInfo, streamOptions, addToHistory, runspace); try { driver.Start(); } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); // Pop runspace on error. _remoteHost.PopRunspace(); throw; } }
/// <summary> /// Handle the invocation of command discovery pipeline /// </summary> /// <param name="sender">sender of this event, unused</param> /// <param name="eventArgs">arguments describing this event</param> private void HandleGetCommandMetadata(object sender, RemoteDataEventArgs<RemoteDataObject<PSObject>> eventArgs) { RemoteDataObject<PSObject> data = eventArgs.Data; PowerShell countingPipeline = RemotingDecoder.GetCommandDiscoveryPipeline(data.Data); if (this.DoesInitialSessionStateIncludeGetCommandWithListImportedSwitch()) { countingPipeline.AddParameter("ListImported", true); } countingPipeline .AddParameter("ErrorAction", "SilentlyContinue") .AddCommand("Measure-Object") .AddCommand("Select-Object") .AddParameter("Property", "Count"); PowerShell mainPipeline = RemotingDecoder.GetCommandDiscoveryPipeline(data.Data); if (this.DoesInitialSessionStateIncludeGetCommandWithListImportedSwitch()) { mainPipeline.AddParameter("ListImported", true); } mainPipeline .AddCommand("Select-Object") .AddParameter("Property", new string[] { "Name", "Namespace", "HelpUri", "CommandType", "ResolvedCommandName", "OutputType", "Parameters" }); HostInfo useRunspaceHost = new HostInfo(null); useRunspaceHost.UseRunspaceHost = true; if (_remoteHost.IsRunspacePushed) { // If we have a pushed runspace then execute there. StartPowerShellCommandOnPushedRunspace( countingPipeline, mainPipeline, data.PowerShellId, data.RunspacePoolId, useRunspaceHost, 0, true, false); } else { // Run on usual driver. ServerPowerShellDriver driver = new ServerPowerShellDriver( countingPipeline, mainPipeline, true /* no input */, data.PowerShellId, data.RunspacePoolId, this, #if !CORECLR // No ApartmentState In CoreCLR ApartmentState.Unknown, #endif useRunspaceHost, 0 /* stream options */, false /* addToHistory */, null /* use default rsPool runspace */); driver.Start(); } }
private void HandleRunspaceCreated(object sender, RunspaceCreatedEventArgs args) { try { string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); args.Runspace.ExecutionContext.EngineSessionState.SetLocation(folderPath); } catch (ArgumentException ex) { } catch (ProviderNotFoundException ex) { } catch (DriveNotFoundException ex) { } catch (ProviderInvocationException ex) { } Command command = (Command)null; if (!string.IsNullOrEmpty(this.configData.StartupScript)) { command = new Command(this.configData.StartupScript, false, false); } else if (!string.IsNullOrEmpty(this.configData.InitializationScriptForOutOfProcessRunspace)) { command = new Command(this.configData.InitializationScriptForOutOfProcessRunspace, true, false); } if (command == null) { return; } HostInfo hostInfo = this.remoteHost.HostInfo; command.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); PowerShell powershell = PowerShell.Create(); powershell.AddCommand(command).AddCommand("out-default"); IAsyncResult asyncResult = new ServerPowerShellDriver(powershell, (PowerShell)null, true, Guid.Empty, this.InstanceId, this, args.Runspace.ApartmentState, hostInfo, RemoteStreamOptions.AddInvocationInfo, false, args.Runspace).Start(); powershell.EndInvoke(asyncResult); ArrayList dollarErrorVariable = (ArrayList)powershell.Runspace.GetExecutionContext.DollarErrorVariable; if (dollarErrorVariable.Count > 0) { string str = (dollarErrorVariable[0] as ErrorRecord).ToString(); throw ServerRunspacePoolDriver.tracer.NewInvalidOperationException("RemotingErrorIdStrings", PSRemotingErrorId.StartupScriptThrewTerminatingError.ToString(), (object)str); } if (this.localRunspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Opening) { return; } object valueToConvert = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData"); if (valueToConvert == null) { return; } this.applicationPrivateData = (PSPrimitiveDictionary)LanguagePrimitives.ConvertTo(valueToConvert, typeof(PSPrimitiveDictionary), true, (IFormatProvider)CultureInfo.InvariantCulture, (TypeTable)null); }
private PSDataCollection<PSObject> InvokePowerShell(PowerShell powershell, RunspaceCreatedEventArgs args) { string str; HostInfo hostInfo = this.remoteHost.HostInfo; IAsyncResult asyncResult = new ServerPowerShellDriver(powershell, null, true, Guid.Empty, this.InstanceId, this, args.Runspace.ApartmentState, hostInfo, RemoteStreamOptions.AddInvocationInfo, false, args.Runspace).Start(); PSDataCollection<PSObject> datas = powershell.EndInvoke(asyncResult); ArrayList dollarErrorVariable = (ArrayList) powershell.Runspace.GetExecutionContext.DollarErrorVariable; if (dollarErrorVariable.Count <= 0) { return datas; } ErrorRecord record = dollarErrorVariable[0] as ErrorRecord; if (record != null) { str = record.ToString(); } else { Exception exception = dollarErrorVariable[0] as Exception; if (exception != null) { str = (exception.Message != null) ? exception.Message : string.Empty; } else { str = string.Empty; } } throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings", PSRemotingErrorId.StartupScriptThrewTerminatingError.ToString(), new object[] { str }); }
private void HandleCreateAndInvokePowerShell (object sender, RemoteDataEventArgs<RemoteDataObject<PSObject>> eventArgs) { RemoteDataObject<PSObject> data = eventArgs.Data; HostInfo hostInfo = RemotingDecoder.GetHostInfo (data.Data); ApartmentState apartmentState = RemotingDecoder.GetApartmentState (data.Data); RemoteStreamOptions remoteStreamOptions = RemotingDecoder.GetRemoteStreamOptions (data.Data); PowerShell powerShell = RemotingDecoder.GetPowerShell (data.Data); bool noInput = RemotingDecoder.GetNoInput(data.Data); bool addToHistory = RemotingDecoder.GetAddToHistory(data.Data); bool isNested = false; if (this.serverCapability.ProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM) { isNested = RemotingDecoder.GetIsNested(data.Data); } if (isNested) { if (this.dsHandler.GetAssociatedPowerShellDataStructureHandler(powerShell.InstanceId) != null) { throw new InvalidOperationException("NestedPipeline is not supported in this release."); } powerShell.SetIsNested(false); if ((this.localRunspacePool.GetMaxRunspaces() == 1) && (this.dsHandler.GetPowerShellDataStructureHandler() != null)) { new ServerSteppablePipelineDriver(powerShell, noInput, data.PowerShellId, data.RunspacePoolId, this, apartmentState, hostInfo, remoteStreamOptions, addToHistory, this.rsToUseForSteppablePipeline, this.eventSubscriber, this.inputCollection).Start(); return; } } ServerPowerShellDriver driver2 = new ServerPowerShellDriver(powerShell, null, noInput, data.PowerShellId, data.RunspacePoolId, this, apartmentState, hostInfo, remoteStreamOptions, addToHistory, null); this.inputCollection = driver2.InputCollection; driver2.Start(); }