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;
 }
Esempio n. 2
0
        /// <summary>
        /// Constructor for ServerRemoteHost.
        /// </summary>
        internal ServerRemoteHost(
            Guid clientRunspacePoolId,
            Guid clientPowerShellId,
            HostInfo hostInfo,
            AbstractServerTransportManager transportManager,
            Runspace runspace,
            ServerDriverRemoteHost serverDriverRemoteHost)
        {
            _clientRunspacePoolId = clientRunspacePoolId;
            _clientPowerShellId = clientPowerShellId;
            Dbg.Assert(hostInfo != null, "Expected hostInfo != null");
            Dbg.Assert(transportManager != null, "Expected transportManager != null");

            // Set host-info and the transport-manager.
            HostInfo = hostInfo;
            _transportManager = transportManager;
            _serverDriverRemoteHost = serverDriverRemoteHost;

            // Create the executor for the host methods.
            _serverMethodExecutor = new ServerMethodExecutor(
                clientRunspacePoolId, clientPowerShellId, _transportManager);

            // Use HostInfo to create host-UI as null or non-null based on the client's host-UI.
            _remoteHostUserInterface = hostInfo.IsHostUINull ? null : new ServerRemoteHostUserInterface(this);

            Runspace = runspace;
        }
Esempio n. 3
0
        private IRSPDriverInvoke _psDriverInvoker;  // Handles nested invocation of PS drivers.

        #endregion Private Members

        #region Constructors

#if !CORECLR
        /// <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>
        internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId,
            Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver,
            ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions,
            bool addToHistory, Runspace rsToUse)
            : this(powershell, extraPowerShell, noInput, clientPowerShellId, clientRunspacePoolId, runspacePoolDriver,
                   apartmentState, hostInfo, streamOptions, addToHistory, rsToUse, null)
        {
        }
Esempio n. 4
0
 internal ServerRemoteHost(
     Guid clientRunspacePoolId,
     Guid clientPowerShellId,
     HostInfo hostInfo,
     AbstractServerTransportManager transportManager)
 {
     this._clientRunspacePoolId    = clientRunspacePoolId;
     this._clientPowerShellId      = clientPowerShellId;
     this._hostInfo                = hostInfo;
     this._transportManager        = transportManager;
     this._serverMethodExecutor    = new ServerMethodExecutor(clientRunspacePoolId, clientPowerShellId, this._transportManager);
     this._remoteHostUserInterface = hostInfo.IsHostUINull ? (ServerRemoteHostUserInterface)null : new ServerRemoteHostUserInterface(this);
 }
 internal ServerRemoteHost GetHostAssociatedWithPowerShell(HostInfo powerShellHostInfo, ServerRemoteHost runspaceServerRemoteHost)
 {
     HostInfo hostInfo;
     if (powerShellHostInfo.UseRunspaceHost)
     {
         hostInfo = runspaceServerRemoteHost.HostInfo;
     }
     else
     {
         hostInfo = powerShellHostInfo;
     }
     return new ServerRemoteHost(this.clientRunspacePoolId, this.clientPowerShellId, hostInfo, this.transportManager);
 }
Esempio n. 6
0
 private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createRunspaceEventArg)
 {
     using (ServerRemoteSession._trace.TraceMethod())
     {
         RemoteDataObject <PSObject> remoteDataObject = createRunspaceEventArg != null ? createRunspaceEventArg.ReceivedData : throw ServerRemoteSession._trace.NewArgumentNullException(nameof(createRunspaceEventArg));
         if (this._context != null)
         {
             this._senderInfo.ClientTimeZone = this._context.ClientCapability.TimeZone;
         }
         this._senderInfo.ApplicationArguments = RemotingDecoder.GetApplicationArguments(remoteDataObject.Data);
         ConfigurationDataFromXML configData = PSSessionConfiguration.LoadEndPointConfiguration(this._configProviderId, this._initParameters);
         configData.InitializationScriptForOutOfProcessRunspace = this._initScriptForOutOfProcRS;
         this.maxRecvdObjectSize      = configData.MaxReceivedObjectSizeMB;
         this.maxRecvdDataSizeCommand = configData.MaxReceivedCommandSizeMB;
         this._sessionConfigProvider  = configData.CreateEndPointConfigurationInstance();
         PSPrimitiveDictionary applicationPrivateData = this._sessionConfigProvider.GetApplicationPrivateData(this._senderInfo);
         InitialSessionState   initialSessionState    = this._sessionConfigProvider.GetInitialSessionState(this._senderInfo);
         if (initialSessionState == null)
         {
             throw ServerRemoteSession._trace.NewInvalidOperationException("RemotingErrorIdStrings", "InitialSessionStateNull", (object)this._configProviderId);
         }
         initialSessionState.ThrowOnRunspaceOpenError = true;
         initialSessionState.Variables.Add(new SessionStateVariableEntry("PSSenderInfo", (object)this._senderInfo, PSRemotingErrorInvariants.FormatResourceString(PSRemotingErrorId.PSSenderInfoDescription), ScopedItemOptions.ReadOnly));
         if (!string.IsNullOrEmpty(configData.EndPointConfigurationTypeName))
         {
             this.maxRecvdObjectSize      = this._sessionConfigProvider.GetMaximumReceivedObjectSize(this._senderInfo);
             this.maxRecvdDataSizeCommand = this._sessionConfigProvider.GetMaximumReceivedDataSizePerCommand(this._senderInfo);
         }
         this._sessionDSHandler.TransportManager.ReceivedDataCollection.MaximumReceivedObjectSize = this.maxRecvdObjectSize;
         Guid            runspacePoolId = remoteDataObject.RunspacePoolId;
         int             minRunspaces   = RemotingDecoder.GetMinRunspaces(remoteDataObject.Data);
         int             maxRunspaces   = RemotingDecoder.GetMaxRunspaces(remoteDataObject.Data);
         PSThreadOptions threadOptions  = RemotingDecoder.GetThreadOptions(remoteDataObject.Data);
         ApartmentState  apartmentState = RemotingDecoder.GetApartmentState((object)remoteDataObject.Data);
         HostInfo        hostInfo       = RemotingDecoder.GetHostInfo(remoteDataObject.Data);
         if (this._runspacePoolDriver != null)
         {
             throw new PSRemotingDataStructureException(PSRemotingErrorId.RunspaceAlreadyExists, new object[1]
             {
                 (object)this._runspacePoolDriver.InstanceId
             });
         }
         bool isAdministrator = this._senderInfo.UserInfo.IsInRole(WindowsBuiltInRole.Administrator);
         this._runspacePoolDriver         = new ServerRunspacePoolDriver(runspacePoolId, minRunspaces, maxRunspaces, threadOptions, apartmentState, hostInfo, initialSessionState, applicationPrivateData, configData, this.SessionDataStructureHandler.TransportManager, isAdministrator, this._context.ServerCapability);
         this._runspacePoolDriver.Closed += new EventHandler <EventArgs>(this.HandleResourceClosing);
         this._runspacePoolDriver.Start();
     }
 }
Esempio n. 7
0
 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;
         }
     }
 }
Esempio n. 8
0
 internal ServerRunspacePoolDriver(Guid clientRunspacePoolId, int minRunspaces, int maxRunspaces, PSThreadOptions threadOptions, ApartmentState apartmentState, HostInfo hostInfo, InitialSessionState initialSessionState, PSPrimitiveDictionary applicationPrivateData, ConfigurationDataFromXML configData, AbstractServerSessionTransportManager transportManager, bool isAdministrator, RemoteSessionCapability serverCapability, Hashtable configHash)
 {
     this.serverCapability = serverCapability;
     System.Management.Automation.Remoting.ServerRemoteHost host = new System.Management.Automation.Remoting.ServerRemoteHost(clientRunspacePoolId, Guid.Empty, hostInfo, transportManager);
     this.remoteHost = host;
     this.configData = configData;
     this.configHash = configHash;
     this.applicationPrivateData = applicationPrivateData;
     this.localRunspacePool = RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces, initialSessionState, host);
     PSThreadOptions options = configData.ShellThreadOptions.HasValue ? configData.ShellThreadOptions.Value : PSThreadOptions.UseCurrentThread;
     if ((threadOptions == PSThreadOptions.Default) || (threadOptions == options))
     {
         this.localRunspacePool.ThreadOptions = options;
     }
     else
     {
         if (!isAdministrator)
         {
             throw new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.MustBeAdminToOverrideThreadOptions, new object[0]));
         }
         this.localRunspacePool.ThreadOptions = threadOptions;
     }
     ApartmentState state = configData.ShellThreadApartmentState.HasValue ? configData.ShellThreadApartmentState.Value : ApartmentState.Unknown;
     if ((apartmentState == ApartmentState.Unknown) || (apartmentState == state))
     {
         this.localRunspacePool.ApartmentState = state;
     }
     else
     {
         this.localRunspacePool.ApartmentState = apartmentState;
     }
     this.clientRunspacePoolId = clientRunspacePoolId;
     this.dsHandler = new ServerRunspacePoolDataStructureHandler(this, transportManager);
     this.localRunspacePool.StateChanged += new EventHandler<RunspacePoolStateChangedEventArgs>(this.HandleRunspacePoolStateChanged);
     this.localRunspacePool.ForwardEvent += new EventHandler<PSEventArgs>(this.HandleRunspacePoolForwardEvent);
     this.localRunspacePool.RunspaceCreated += new EventHandler<RunspaceCreatedEventArgs>(this.HandleRunspaceCreated);
     this.localRunspacePool.RunspaceCreated += new EventHandler<RunspaceCreatedEventArgs>(this.HandleRunspaceCreatedForTypeTable);
     this.dsHandler.CreateAndInvokePowerShell += new EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>>(this.HandleCreateAndInvokePowerShell);
     this.dsHandler.GetCommandMetadata += new EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>>(this.HandleGetCommandMetadata);
     this.dsHandler.HostResponseReceived += new EventHandler<RemoteDataEventArgs<RemoteHostResponse>>(this.HandleHostResponseReceived);
     this.dsHandler.SetMaxRunspacesReceived += new EventHandler<RemoteDataEventArgs<PSObject>>(this.HandleSetMaxRunspacesReceived);
     this.dsHandler.SetMinRunspacesReceived += new EventHandler<RemoteDataEventArgs<PSObject>>(this.HandleSetMinRunspacesReceived);
     this.dsHandler.GetAvailableRunspacesReceived += new EventHandler<RemoteDataEventArgs<PSObject>>(this.HandleGetAvailalbeRunspacesReceived);
 }
Esempio n. 9
0
 /// <summary>
 /// Creates the runspace pool driver
 /// </summary>
 /// <param name="clientRunspacePoolId">client runspace pool id to associate</param>
 /// <param name="transportManager">transport manager associated with this
 /// runspace pool driver</param>
 /// <param name="maxRunspaces">maximum runspaces to open</param>
 /// <param name="minRunspaces">minimum runspaces to open</param>
 /// <param name="threadOptions">threading options for the runspaces in the pool</param>        
 /// <param name="hostInfo">host information about client side host</param>
 /// <param name="configData">
 /// Contains:
 /// 1. Script to run after a RunspacePool/Runspace is created in this session.
 /// For RunspacePool case, every newly created Runspace (in the pool) will run
 /// this script.
 /// 2. ThreadOptions for RunspacePool/Runspace
 /// 3. ThreadApartment for RunspacePool/Runspace
 /// </param>
 /// <param name="initialSessionState">configuration of the runspace</param>
 /// <param name="applicationPrivateData">application private data</param>
 /// <param name="isAdministrator">True if the driver is being created by an administrator</param>
 /// <param name="serverCapability">server capability reported to the client during negotiation (not the actual capability)</param>
 /// <param name="psClientVersion">Client PowerShell version.</param>
 /// <param name="configurationName">Optional endpoint configuration name to create a pushed configured runspace.</param>
 internal ServerRunspacePoolDriver(
     Guid clientRunspacePoolId,
     int minRunspaces,
     int maxRunspaces,
     PSThreadOptions threadOptions,
     HostInfo hostInfo,
     InitialSessionState initialSessionState,
     PSPrimitiveDictionary applicationPrivateData,
     ConfigurationDataFromXML configData,
     AbstractServerSessionTransportManager transportManager,
     bool isAdministrator,
     RemoteSessionCapability serverCapability,
     Version psClientVersion,
     string configurationName)
Esempio n. 10
0
        /// <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;
            }
        }
Esempio n. 11
0
        /// <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();
            }
        }
Esempio n. 12
0
 private void HandleGetCommandMetadata(object sender, RemoteDataEventArgs<RemoteDataObject<PSObject>> eventArgs)
 {
     RemoteDataObject<PSObject> data = eventArgs.Data;
     PowerShell commandDiscoveryPipeline = RemotingDecoder.GetCommandDiscoveryPipeline(data.Data);
     if (this.DoesInitialSessionStateIncludeGetCommandWithListImportedSwitch())
     {
         commandDiscoveryPipeline.AddParameter("ListImported", true);
     }
     commandDiscoveryPipeline.AddParameter("ErrorAction", "SilentlyContinue").AddCommand("Measure-Object").AddCommand("Select-Object").AddParameter("Property", "Count");
     PowerShell extraPowerShell = RemotingDecoder.GetCommandDiscoveryPipeline(data.Data);
     if (this.DoesInitialSessionStateIncludeGetCommandWithListImportedSwitch())
     {
         extraPowerShell.AddParameter("ListImported", true);
     }
     extraPowerShell.AddCommand("Select-Object").AddParameter("Property", new string[] { "Name", "Namespace", "HelpUri", "CommandType", "ResolvedCommandName", "OutputType", "Parameters" });
     HostInfo hostInfo = new HostInfo(null) {
         UseRunspaceHost = true
     };
     new ServerPowerShellDriver(commandDiscoveryPipeline, extraPowerShell, true, data.PowerShellId, data.RunspacePoolId, this, ApartmentState.Unknown, hostInfo, 0, false, null).Start();
 }
        /// <summary>
        /// Default constructor for creating ServerSteppablePipelineDriver...Used by server to concurrently
        /// run 2 pipelines.
        /// </summary>
        /// <param name="powershell">decoded powershell object</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="eventSubscriber">
        /// Steppable pipeline event subscriber
        /// </param>
        /// <param name="powershellInput">input collection of the PowerShell pipeline</param>
        internal ServerSteppablePipelineDriver(PowerShell powershell, bool noInput, Guid clientPowerShellId,
            Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver,
            ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions,
            bool addToHistory, Runspace rsToUse, ServerSteppablePipelineSubscriber eventSubscriber, PSDataCollection<object> powershellInput)
#endif
        {
            LocalPowerShell = powershell;
            InstanceId = clientPowerShellId;
            RunspacePoolId = clientRunspacePoolId;
            RemoteStreamOptions = streamOptions;
#if !CORECLR // No ApartmentState In CoreCLR
            this.apartmentState = apartmentState;
#endif
            NoInput = noInput;
            _addToHistory = addToHistory;
            _eventSubscriber = eventSubscriber;
            _powershellInput = powershellInput;

            Input = new PSDataCollection<object>();
            InputEnumerator = Input.GetEnumerator();
            Input.ReleaseOnEnumeration = true;

            DataStructureHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, RemoteStreamOptions, null);
            RemoteHost = DataStructureHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost);

            // subscribe to various data structure handler events
            DataStructureHandler.InputEndReceived += new EventHandler(HandleInputEndReceived);
            DataStructureHandler.InputReceived += new EventHandler<RemoteDataEventArgs<object>>(HandleInputReceived);
            DataStructureHandler.StopPowerShellReceived += new EventHandler(HandleStopReceived);
            DataStructureHandler.HostResponseReceived +=
                new EventHandler<RemoteDataEventArgs<RemoteHostResponse>>(HandleHostResponseReceived);
            DataStructureHandler.OnSessionConnected += new EventHandler(HandleSessionConnected);

            if (rsToUse == null)
            {
                throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.NestedPipelineMissingRunspace);
            }

            // else, set the runspace pool and invoke this powershell
            LocalPowerShell.Runspace = rsToUse;
            eventSubscriber.SubscribeEvents(this);

            PipelineState = PSInvocationState.NotStarted;
        }
        private PSDataCollection<object> _powershellInput; // input collection of the PowerShell pipeline

        #endregion

#if CORECLR // No ApartmentState In CoreCLR
        /// <summary>
        /// Default constructor for creating ServerSteppablePipelineDriver...Used by server to concurrently
        /// run 2 pipelines.
        /// </summary>
        /// <param name="powershell">decoded powershell object</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="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="eventSubscriber">
        /// Steppable pipeline event subscriber
        /// </param>
        /// <param name="powershellInput">input collection of the PowerShell pipeline</param>
        internal ServerSteppablePipelineDriver(PowerShell powershell, bool noInput, Guid clientPowerShellId,
            Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver,
            HostInfo hostInfo, RemoteStreamOptions streamOptions,
            bool addToHistory, Runspace rsToUse, ServerSteppablePipelineSubscriber eventSubscriber, PSDataCollection<object> powershellInput)
Esempio n. 15
0
        /// <summary>
        /// Creates a ServerRemoteHost which is associated with this powershell.
        /// </summary>
        /// <param name="powerShellHostInfo">Host information about the host associated 
        /// PowerShell object on the client.</param>
        /// <param name="runspaceServerRemoteHost">Host associated with the RunspacePool
        /// on the server.</param>
        /// <returns>A new ServerRemoteHost for the PowerShell.</returns>
        internal ServerRemoteHost GetHostAssociatedWithPowerShell(
            HostInfo powerShellHostInfo,
            ServerRemoteHost runspaceServerRemoteHost)
        {
            HostInfo hostInfo;

            // If host was null use the runspace's host for this powershell; otherwise, 
            // use the HostInfo to create a proxy host of the powershell's host.
            if (powerShellHostInfo.UseRunspaceHost)
            {
                hostInfo = runspaceServerRemoteHost.HostInfo;
            }
            else
            {
                hostInfo = powerShellHostInfo;
            }

            // If the host was not null on the client, then the PowerShell object should 
            // get a brand spanking new host.
            return new ServerRemoteHost(_clientRunspacePoolId, _clientPowerShellId, hostInfo,
                _transportManager, runspaceServerRemoteHost.Runspace, runspaceServerRemoteHost as ServerDriverRemoteHost);
        }
Esempio n. 16
0
        /// <summary>
        /// Creates the runspace pool driver
        /// </summary>
        /// <param name="clientRunspacePoolId">client runspace pool id to associate</param>
        /// <param name="transportManager">transport manager associated with this
        /// runspace pool driver</param>
        /// <param name="maxRunspaces">maximum runspaces to open</param>
        /// <param name="minRunspaces">minimum runspaces to open</param>
        /// <param name="threadOptions">threading options for the runspaces in the pool</param>
        /// <param name="apartmentState">apartment state for the runspaces in the pool</param>
        /// <param name="hostInfo">host information about client side host</param>
        /// <param name="configData">
        /// Contains:
        /// 1. Script to run after a RunspacePool/Runspace is created in this session.
        /// For RunspacePool case, every newly created Runspace (in the pool) will run
        /// this script.
        /// 2. ThreadOptions for RunspacePool/Runspace
        /// 3. ThreadApartment for RunspacePool/Runspace
        /// </param>
        /// <param name="initialSessionState">configuration of the runspace</param>
        /// <param name="applicationPrivateData">application private data</param>
        /// <param name="isAdministrator">True if the driver is being created by an administrator</param>
        /// <param name="serverCapability">server capability reported to the client during negotiation (not the actual capability)</param>
        /// <param name="psClientVersion">Client PowerShell version.</param>
        /// <param name="configurationName">Optional endpoint configuration name to create a pushed configured runspace.</param>
        internal ServerRunspacePoolDriver(
            Guid clientRunspacePoolId,
            int minRunspaces,
            int maxRunspaces,
            PSThreadOptions threadOptions,
            ApartmentState apartmentState,
            HostInfo hostInfo,
            InitialSessionState initialSessionState,
            PSPrimitiveDictionary applicationPrivateData,
            ConfigurationDataFromXML configData,
            AbstractServerSessionTransportManager transportManager,
            bool isAdministrator,
            RemoteSessionCapability serverCapability,
            Version psClientVersion,
            string configurationName)
#endif
        {
            Dbg.Assert(null != configData, "ConfigurationData cannot be null");

            _serverCapability = serverCapability;
            _clientPSVersion = psClientVersion;

            _configurationName = configurationName;

            // Create a new server host and associate for host call
            // integration
            _remoteHost = new ServerDriverRemoteHost(clientRunspacePoolId,
                Guid.Empty, hostInfo, transportManager, null);

            _configData = configData;
            _applicationPrivateData = applicationPrivateData;
            RunspacePool = RunspaceFactory.CreateRunspacePool(
                  minRunspaces, maxRunspaces, initialSessionState, _remoteHost);

            // Set ThreadOptions for this RunspacePool
            // The default server settings is to make new commands execute in the calling thread...this saves
            // thread switching time and thread pool pressure on the service.
            // Users can override the server settings only if they are administrators
            PSThreadOptions serverThreadOptions = configData.ShellThreadOptions.HasValue ? configData.ShellThreadOptions.Value : PSThreadOptions.UseCurrentThread;
            if (threadOptions == PSThreadOptions.Default || threadOptions == serverThreadOptions)
            {
                RunspacePool.ThreadOptions = serverThreadOptions;
            }
            else
            {
                if (!isAdministrator)
                {
                    throw new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.MustBeAdminToOverrideThreadOptions));
                }

                RunspacePool.ThreadOptions = threadOptions;
            }

#if !CORECLR // No ApartmentState In CoreCLR
            // Set Thread ApartmentState for this RunspacePool
            ApartmentState serverApartmentState = configData.ShellThreadApartmentState.HasValue ? configData.ShellThreadApartmentState.Value : Runspace.DefaultApartmentState;

            if (apartmentState == ApartmentState.Unknown || apartmentState == serverApartmentState)
            {
                RunspacePool.ApartmentState = serverApartmentState;
            }
            else
            {
                RunspacePool.ApartmentState = apartmentState;
            }
#endif

            // If we have a runspace pool with a single runspace then we can run nested pipelines on
            // on it in a single pipeline invoke thread.
            if (maxRunspaces == 1 &&
                (RunspacePool.ThreadOptions == PSThreadOptions.Default ||
                 RunspacePool.ThreadOptions == PSThreadOptions.UseCurrentThread))
            {
                _driverNestedInvoker = new PowerShellDriverInvoker();
            }

            InstanceId = clientRunspacePoolId;
            DataStructureHandler = new ServerRunspacePoolDataStructureHandler(this, transportManager);

            // handle the StateChanged event of the runspace pool
            RunspacePool.StateChanged +=
                new EventHandler<RunspacePoolStateChangedEventArgs>(HandleRunspacePoolStateChanged);

            // listen for events on the runspace pool
            RunspacePool.ForwardEvent +=
                new EventHandler<PSEventArgs>(HandleRunspacePoolForwardEvent);

            RunspacePool.RunspaceCreated += HandleRunspaceCreated;

            // register for all the events from the data structure handler
            DataStructureHandler.CreateAndInvokePowerShell +=
                new EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>>(HandleCreateAndInvokePowerShell);
            DataStructureHandler.GetCommandMetadata +=
                new EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>>(HandleGetCommandMetadata);
            DataStructureHandler.HostResponseReceived +=
                new EventHandler<RemoteDataEventArgs<RemoteHostResponse>>(HandleHostResponseReceived);
            DataStructureHandler.SetMaxRunspacesReceived +=
                new EventHandler<RemoteDataEventArgs<PSObject>>(HandleSetMaxRunspacesReceived);
            DataStructureHandler.SetMinRunspacesReceived +=
                new EventHandler<RemoteDataEventArgs<PSObject>>(HandleSetMinRunspacesReceived);
            DataStructureHandler.GetAvailableRunspacesReceived +=
                new EventHandler<RemoteDataEventArgs<PSObject>>(HandleGetAvailableRunspacesReceived);
            DataStructureHandler.ResetRunspaceState +=
                new EventHandler<RemoteDataEventArgs<PSObject>>(HandleResetRunspaceState);
        }
Esempio n. 17
0
 internal ServerDriverRemoteHost(
     Guid clientRunspacePoolId,
     Guid clientPowerShellId,
     HostInfo hostInfo,
     AbstractServerSessionTransportManager transportManager,
     ServerRemoteDebugger debugger)
     : base(clientRunspacePoolId, clientPowerShellId, hostInfo, transportManager, null, null)
 {
     _debugger = debugger;
 }
Esempio n. 18
0
        /// <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);
                            }
                        }
                    };
            }
        }
Esempio n. 19
0
 /// <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="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,
     HostInfo hostInfo, RemoteStreamOptions streamOptions,
     bool addToHistory, Runspace rsToUse, PSDataCollection<PSObject> output)
Esempio n. 20
0
        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();
            }
        }
Esempio n. 21
0
        private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createRunspaceEventArg)
        {
            if (createRunspaceEventArg == null)
            {
                throw PSTraceSource.NewArgumentNullException("createRunspaceEventArg");
            }
            RemoteDataObject <PSObject> receivedData = createRunspaceEventArg.ReceivedData;

            if (this._context != null)
            {
                if (this._context.ClientCapability == null)
                {
                    this._senderInfo.ClientTimeZone = this._context.ServerCapability.TimeZone;
                }
                else
                {
                    this._senderInfo.ClientTimeZone = this._context.ClientCapability.TimeZone;
                }
            }
            this._senderInfo.ApplicationArguments = RemotingDecoder.GetApplicationArguments(receivedData.Data);
            ConfigurationDataFromXML configData = PSSessionConfiguration.LoadEndPointConfiguration(this._configProviderId, this._initParameters);

            configData.InitializationScriptForOutOfProcessRunspace = this._initScriptForOutOfProcRS;
            this.maxRecvdObjectSize      = configData.MaxReceivedObjectSizeMB;
            this.maxRecvdDataSizeCommand = configData.MaxReceivedCommandSizeMB;
            DISCPowerShellConfiguration configuration = null;

            if (string.IsNullOrEmpty(configData.ConfigFilePath))
            {
                this._sessionConfigProvider = configData.CreateEndPointConfigurationInstance();
            }
            else
            {
                configuration = new DISCPowerShellConfiguration(configData.ConfigFilePath);
                this._sessionConfigProvider = configuration;
            }
            PSPrimitiveDictionary applicationPrivateData = this._sessionConfigProvider.GetApplicationPrivateData(this._senderInfo);
            InitialSessionState   initialSessionState    = null;

            if (configData.SessionConfigurationData != null)
            {
                try
                {
                    initialSessionState = this._sessionConfigProvider.GetInitialSessionState(configData.SessionConfigurationData, this._senderInfo, this._configProviderId);
                }
                catch (NotImplementedException)
                {
                    initialSessionState = this._sessionConfigProvider.GetInitialSessionState(this._senderInfo);
                }
            }
            else
            {
                initialSessionState = this._sessionConfigProvider.GetInitialSessionState(this._senderInfo);
            }
            if (initialSessionState == null)
            {
                throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings", "InitialSessionStateNull", new object[] { this._configProviderId });
            }
            initialSessionState.ThrowOnRunspaceOpenError = true;
            initialSessionState.Variables.Add(new SessionStateVariableEntry("PSSenderInfo", this._senderInfo, PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.PSSenderInfoDescription, new object[0]), ScopedItemOptions.ReadOnly));
            if ((this._senderInfo.ApplicationArguments != null) && this._senderInfo.ApplicationArguments.ContainsKey("PSversionTable"))
            {
                PSPrimitiveDictionary dictionary2 = PSObject.Base(this._senderInfo.ApplicationArguments["PSversionTable"]) as PSPrimitiveDictionary;
                if ((dictionary2 != null) && dictionary2.ContainsKey("WSManStackVersion"))
                {
                    Version version = PSObject.Base(dictionary2["WSManStackVersion"]) as Version;
                    if ((version != null) && (version.Major < 3))
                    {
                        initialSessionState.Commands.Add(new SessionStateFunctionEntry("TabExpansion", "\r\n            param($line, $lastWord)\r\n            & {\r\n                function Write-Members ($sep='.')\r\n                {\r\n                    Invoke-Expression ('$_val=' + $_expression)\r\n\r\n                    $_method = [Management.Automation.PSMemberTypes] `\r\n                        'Method,CodeMethod,ScriptMethod,ParameterizedProperty'\r\n                    if ($sep -eq '.')\r\n                    {\r\n                        $params = @{view = 'extended','adapted','base'}\r\n                    }\r\n                    else\r\n                    {\r\n                        $params = @{static=$true}\r\n                    }\r\n        \r\n                    foreach ($_m in ,$_val | Get-Member @params $_pat |\r\n                        Sort-Object membertype,name)\r\n                    {\r\n                        if ($_m.MemberType -band $_method)\r\n                        {\r\n                            # Return a method...\r\n                            $_base + $_expression + $sep + $_m.name + '('\r\n                        }\r\n                        else {\r\n                            # Return a property...\r\n                            $_base + $_expression + $sep + $_m.name\r\n                        }\r\n                    }\r\n                }\r\n\r\n                # If a command name contains any of these chars, it needs to be quoted\r\n                $_charsRequiringQuotes = ('`&@''#{}()$,;|<> ' + \"`t\").ToCharArray()\r\n\r\n                # If a variable name contains any of these characters it needs to be in braces\r\n                $_varsRequiringQuotes = ('-`&@''#{}()$,;|<> .\\/' + \"`t\").ToCharArray()\r\n\r\n                switch -regex ($lastWord)\r\n                {\r\n                    # Handle property and method expansion rooted at variables...\r\n                    # e.g. $a.b.<tab>\r\n                    '(^.*)(\\$(\\w|:|\\.)+)\\.([*\\w]*)$' {\r\n                        $_base = $matches[1]\r\n                        $_expression = $matches[2]\r\n                        $_pat = $matches[4] + '*'\r\n                        Write-Members\r\n                        break;\r\n                    }\r\n\r\n                    # Handle simple property and method expansion on static members...\r\n                    # e.g. [datetime]::n<tab>\r\n                    '(^.*)(\\[(\\w|\\.|\\+)+\\])(\\:\\:|\\.){0,1}([*\\w]*)$' {\r\n                        $_base = $matches[1]\r\n                        $_expression = $matches[2]\r\n                        $_pat = $matches[5] + '*'\r\n                        Write-Members $(if (! $matches[4]) {'::'} else {$matches[4]})\r\n                        break;\r\n                    }\r\n\r\n                    # Handle complex property and method expansion on static members\r\n                    # where there are intermediate properties...\r\n                    # e.g. [datetime]::now.d<tab>\r\n                    '(^.*)(\\[(\\w|\\.|\\+)+\\](\\:\\:|\\.)(\\w+\\.)+)([*\\w]*)$' {\r\n                        $_base = $matches[1]  # everything before the expression\r\n                        $_expression = $matches[2].TrimEnd('.') # expression less trailing '.'\r\n                        $_pat = $matches[6] + '*'  # the member to look for...\r\n                        Write-Members\r\n                        break;\r\n                    }\r\n\r\n                    # Handle variable name expansion...\r\n                    '(^.*\\$)([*\\w:]+)$' {\r\n                        $_prefix = $matches[1]\r\n                        $_varName = $matches[2]\r\n                        $_colonPos = $_varname.IndexOf(':')\r\n                        if ($_colonPos -eq -1)\r\n                        {\r\n                            $_varName = 'variable:' + $_varName\r\n                            $_provider = ''\r\n                        }\r\n                        else\r\n                        {\r\n                            $_provider = $_varname.Substring(0, $_colonPos+1)\r\n                        }\r\n\r\n                        foreach ($_v in Get-ChildItem ($_varName + '*') | sort Name)\r\n                        { \r\n                            $_nameFound = $_v.name\r\n                            $(if ($_nameFound.IndexOfAny($_varsRequiringQuotes) -eq -1) {'{0}{1}{2}'}\r\n                            else {'{0}{{{1}{2}}}'}) -f $_prefix, $_provider, $_nameFound\r\n                        }\r\n                        break;\r\n                    }\r\n\r\n                    # Do completion on parameters...\r\n                    '^-([*\\w0-9]*)' {\r\n                        $_pat = $matches[1] + '*'\r\n\r\n                        # extract the command name from the string\r\n                        # first split the string into statements and pipeline elements\r\n                        # This doesn't handle strings however.\r\n                        $_command = [regex]::Split($line, '[|;=]')[-1]\r\n\r\n                        #  Extract the trailing unclosed block e.g. ls | foreach { cp\r\n                        if ($_command -match '\\{([^\\{\\}]*)$')\r\n                        {\r\n                            $_command = $matches[1]\r\n                        }\r\n\r\n                        # Extract the longest unclosed parenthetical expression...\r\n                        if ($_command -match '\\(([^()]*)$')\r\n                        {\r\n                            $_command = $matches[1]\r\n                        }\r\n\r\n                        # take the first space separated token of the remaining string\r\n                        # as the command to look up. Trim any leading or trailing spaces\r\n                        # so you don't get leading empty elements.\r\n                        $_command = $_command.TrimEnd('-')\r\n                        $_command,$_arguments = $_command.Trim().Split()\r\n\r\n                        # now get the info object for it, -ArgumentList will force aliases to be resolved\r\n                        # it also retrieves dynamic parameters\r\n                        try\r\n                        {\r\n                            $_command = @(Get-Command -type 'Alias,Cmdlet,Function,Filter,ExternalScript' `\r\n                                -Name $_command -ArgumentList $_arguments)[0]\r\n                        }\r\n                        catch\r\n                        {\r\n                            # see if the command is an alias. If so, resolve it to the real command\r\n                            if(Test-Path alias:\\$_command)\r\n                            {\r\n                                $_command = @(Get-Command -Type Alias $_command)[0].Definition\r\n                            }\r\n\r\n                            # If we were unsuccessful retrieving the command, try again without the parameters\r\n                            $_command = @(Get-Command -type 'Cmdlet,Function,Filter,ExternalScript' `\r\n                                -Name $_command)[0]\r\n                        }\r\n\r\n                        # remove errors generated by the command not being found, and break\r\n                        if(-not $_command) { $error.RemoveAt(0); break; }\r\n\r\n                        # expand the parameter sets and emit the matching elements\r\n                        # need to use psbase.Keys in case 'keys' is one of the parameters\r\n                        # to the cmdlet\r\n                        foreach ($_n in $_command.Parameters.psbase.Keys)\r\n                        {\r\n                            if ($_n -like $_pat) { '-' + $_n }\r\n                        }\r\n                        break;\r\n                    }\r\n\r\n                    # Tab complete against history either #<pattern> or #<id>\r\n                    '^#(\\w*)' {\r\n                        $_pattern = $matches[1]\r\n                        if ($_pattern -match '^[0-9]+$')\r\n                        {\r\n                            Get-History -ea SilentlyContinue -Id $_pattern | Foreach { $_.CommandLine } \r\n                        }\r\n                        else\r\n                        {\r\n                            $_pattern = '*' + $_pattern + '*'\r\n                            Get-History -Count 32767 | Sort-Object -Descending Id| Foreach { $_.CommandLine } | where { $_ -like $_pattern }\r\n                        }\r\n                        break;\r\n                    }\r\n\r\n                    # try to find a matching command...\r\n                    default {\r\n                        # parse the script...\r\n                        $_tokens = [System.Management.Automation.PSParser]::Tokenize($line,\r\n                            [ref] $null)\r\n\r\n                        if ($_tokens)\r\n                        {\r\n                            $_lastToken = $_tokens[$_tokens.count - 1]\r\n                            if ($_lastToken.Type -eq 'Command')\r\n                            {\r\n                                $_cmd = $_lastToken.Content\r\n\r\n                                # don't look for paths...\r\n                                if ($_cmd.IndexOfAny('/\\:') -eq -1)\r\n                                {\r\n                                    # handle parsing errors - the last token string should be the last\r\n                                    # string in the line...\r\n                                    if ($lastword.Length -ge $_cmd.Length -and \r\n                                        $lastword.substring($lastword.length-$_cmd.length) -eq $_cmd)\r\n                                    {\r\n                                        $_pat = $_cmd + '*'\r\n                                        $_base = $lastword.substring(0, $lastword.length-$_cmd.length)\r\n\r\n                                        # get files in current directory first, then look for commands...\r\n                                        $( try {Resolve-Path -ea SilentlyContinue -Relative $_pat } catch {} ;\r\n                                           try { $ExecutionContext.InvokeCommand.GetCommandName($_pat, $true, $false) |\r\n                                               Sort-Object -Unique } catch {} ) |\r\n                                                   # If the command contains non-word characters (space, ) ] ; ) etc.)\r\n                                                   # then it needs to be quoted and prefixed with &\r\n                                                   ForEach-Object {\r\n                                                        if ($_.IndexOfAny($_charsRequiringQuotes) -eq -1) { $_ }\r\n                                                        elseif ($_.IndexOf('''') -ge 0) {'& ''{0}''' -f $_.Replace('''','''''') }\r\n                                                        else { '& ''{0}''' -f $_ }} |\r\n                                                   ForEach-Object {'{0}{1}' -f $_base,$_ }\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        "));
                    }
                }
            }
            if (!string.IsNullOrEmpty(configData.EndPointConfigurationTypeName))
            {
                this.maxRecvdObjectSize      = this._sessionConfigProvider.GetMaximumReceivedObjectSize(this._senderInfo);
                this.maxRecvdDataSizeCommand = this._sessionConfigProvider.GetMaximumReceivedDataSizePerCommand(this._senderInfo);
            }
            this._sessionDSHandler.TransportManager.ReceivedDataCollection.MaximumReceivedObjectSize = this.maxRecvdObjectSize;
            Guid            runspacePoolId = receivedData.RunspacePoolId;
            int             minRunspaces   = RemotingDecoder.GetMinRunspaces(receivedData.Data);
            int             maxRunspaces   = RemotingDecoder.GetMaxRunspaces(receivedData.Data);
            PSThreadOptions threadOptions  = RemotingDecoder.GetThreadOptions(receivedData.Data);
            ApartmentState  apartmentState = RemotingDecoder.GetApartmentState(receivedData.Data);
            HostInfo        hostInfo       = RemotingDecoder.GetHostInfo(receivedData.Data);

            if (this._runspacePoolDriver != null)
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.RunspaceAlreadyExists, new object[] { this._runspacePoolDriver.InstanceId });
            }
            bool isAdministrator            = this._senderInfo.UserInfo.IsInRole(WindowsBuiltInRole.Administrator);
            ServerRunspacePoolDriver driver = new ServerRunspacePoolDriver(runspacePoolId, minRunspaces, maxRunspaces, threadOptions, apartmentState, hostInfo, initialSessionState, applicationPrivateData, configData, this.SessionDataStructureHandler.TransportManager, isAdministrator, this._context.ServerCapability, (configuration == null) ? null : configuration.ConfigHash);

            Interlocked.Exchange <ServerRunspacePoolDriver>(ref this._runspacePoolDriver, driver);
            this._runspacePoolDriver.Closed = (EventHandler <EventArgs>)Delegate.Combine(this._runspacePoolDriver.Closed, new EventHandler <EventArgs>(this.HandleResourceClosing));
            this._runspacePoolDriver.Start();
        }