示例#1
0
 /// <summary>
 /// This constuctor takes an inner exception and an error id.
 /// </summary>
 /// <param name="innerException">
 /// Inner exception.
 /// </param>
 /// <param name="resourceString">
 /// The resource string in the base resource file.
 /// </param>
 /// <param name="args">
 /// Optional parameters required to format the resource string.
 /// </param>
 internal PSRemotingTransportException(Exception innerException, string resourceString, params object[] args)
     : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args), innerException)
 {
     SetDefaultErrorRecord();
 }
示例#2
0
 /// <summary>
 /// This is the default constructor.
 /// </summary>
 public PSRemotingTransportRedirectException()
     : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.DefaultRemotingExceptionMessage,
                                                           typeof(PSRemotingTransportRedirectException).FullName))
 {
     SetDefaultErrorRecord();
 }
示例#3
0
 /// <summary>
 /// This constructor takes an error id and optional parameters.
 /// </summary>
 /// <param name="resourceString">
 /// The resource string in the base resource file.
 /// </param>
 /// <param name="args">
 /// Optional parameters required to format the resource string.
 /// </param>
 internal PSRemotingDataStructureException(string resourceString, params object[] args)
     : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args))
 {
     SetDefaultErrorRecord();
 }
示例#4
0
 /// <summary>
 /// This constructor takes an error id and optional parameters.
 /// </summary>
 /// <param name="errorId">
 /// The error id in the base resource file.
 /// </param>
 /// <param name="resourceString">
 /// The resource string in the base resource file.
 /// </param>
 /// <param name="args">
 /// Optional parameters required to format the resource string.
 /// </param>
 internal PSRemotingTransportException(PSRemotingErrorId errorId, string resourceString, params object[] args)
     : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args))
 {
     SetDefaultErrorRecord();
     _errorCode = (int)errorId;
 }
示例#5
0
 public PSRemotingDataStructureException()
     : base(PSRemotingErrorInvariants.FormatResourceString(PSRemotingErrorId.DefaultRemotingExceptionMessage, (object) typeof(PSRemotingDataStructureException).FullName))
     => this.SetDefaultErrorRecord();
示例#6
0
 internal PSRemotingDataStructureException(PSRemotingErrorId errorId, params object[] args)
     : base(PSRemotingErrorInvariants.FormatResourceString(errorId, args))
     => this.SetDefaultErrorRecord();
 internal static Exception NewRemoteRunspaceDoesNotSupportPushRunspaceException()
 {
     return(new PSRemotingDataStructureException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemoteRunspaceDoesNotSupportPushRunspace, new object[0])));
 }
示例#8
0
 private string ModifyMessage(string message, string computerName)
 {
     return(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemoteHostPromptForCredentialModifiedMessage, new object[] { computerName.ToUpper(CultureInfo.CurrentCulture), message }));
 }
 internal static Exception NewDecodingFailedException()
 {
     return(new PSRemotingDataStructureException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemoteHostDecodingFailed, new object[0])));
 }
示例#10
0
        internal static Exception NewRemoteHostCallFailedException(RemoteHostMethodId methodId)
        {
            RemoteHostMethodInfo info = RemoteHostMethodInfo.LookUp(methodId);

            return(new PSRemotingDataStructureException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemoteHostCallFailed, new object[] { info.Name })));
        }
示例#11
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();
     }
 }
示例#12
0
 private string ModifyMessage(string message, string computerName) => PSRemotingErrorInvariants.FormatResourceString(PSRemotingErrorId.RemoteHostPromptForCredentialModifiedMessage, (object)computerName.ToUpper(CultureInfo.CurrentCulture), (object)message);
示例#13
0
        private RemoteHostCall ConstructWarningMessageForSecureString(string computerName, string resourceString)
        {
            string str = PSRemotingErrorInvariants.FormatResourceString(resourceString, new object[] { computerName.ToUpper(CultureInfo.CurrentCulture) });

            return(new RemoteHostCall(-100L, RemoteHostMethodId.WriteWarningLine, new object[] { str }));
        }
        /// <summary>
        /// Connect to Hyper-V socket server.  This is a blocking call until a
        /// connection occurs or the timeout time has elapsed.
        /// </summary>
        /// <param name="networkCredential">The credential used for authentication.</param>
        /// <param name="configurationName">The configuration name of the PS session.</param>
        /// <param name="isFirstConnection">Whether this is the first connection.</param>
        public bool Connect(
            NetworkCredential networkCredential,
            string configurationName,
            bool isFirstConnection)
        {
            bool result = false;

            //
            // Check invalid input and throw exception before setting up socket connection.
            // This check is done only in VM case.
            //
            if (isFirstConnection)
            {
                if (string.IsNullOrEmpty(networkCredential.UserName))
                {
                    throw new PSDirectException(
                              PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidUsername));
                }
            }

            HyperVSocket.Connect(EndPoint);

            if (HyperVSocket.Connected)
            {
                _tracer.WriteMessage("RemoteSessionHyperVSocketClient", "Connect", Guid.Empty,
                                     "Client connected.");

                Stream = new NetworkStream(HyperVSocket, true);

                if (isFirstConnection)
                {
                    if (string.IsNullOrEmpty(networkCredential.Domain))
                    {
                        networkCredential.Domain = "localhost";
                    }

                    bool emptyPassword      = string.IsNullOrEmpty(networkCredential.Password);
                    bool emptyConfiguration = string.IsNullOrEmpty(configurationName);

                    byte[] domain   = Encoding.Unicode.GetBytes(networkCredential.Domain);
                    byte[] userName = Encoding.Unicode.GetBytes(networkCredential.UserName);
                    byte[] password = Encoding.Unicode.GetBytes(networkCredential.Password);
                    byte[] response = new byte[4]; // either "PASS" or "FAIL"
                    string responseString;

                    //
                    // Send credential to VM so that PowerShell process inside VM can be
                    // created under the correct security context.
                    //
                    HyperVSocket.Send(domain);
                    HyperVSocket.Receive(response);

                    HyperVSocket.Send(userName);
                    HyperVSocket.Receive(response);

                    //
                    // We cannot simply send password because if it is empty,
                    // the vmicvmsession service in VM will block in recv method.
                    //
                    if (emptyPassword)
                    {
                        HyperVSocket.Send(Encoding.ASCII.GetBytes("EMPTYPW"));
                        HyperVSocket.Receive(response);
                        responseString = Encoding.ASCII.GetString(response);
                    }
                    else
                    {
                        HyperVSocket.Send(Encoding.ASCII.GetBytes("NONEMPTYPW"));
                        HyperVSocket.Receive(response);

                        HyperVSocket.Send(password);
                        HyperVSocket.Receive(response);
                        responseString = Encoding.ASCII.GetString(response);
                    }

                    //
                    // There are 3 cases for the responseString received above.
                    // - "FAIL": credential is invalid
                    // - "PASS": credential is valid, but PowerShell Direct in VM does not support configuration (Server 2016 TP4 and before)
                    // - "CONF": credential is valid, and PowerShell Direct in VM supports configuration (Server 2016 TP5 and later)
                    //

                    //
                    // Credential is invalid.
                    //
                    if (string.Compare(responseString, "FAIL", StringComparison.Ordinal) == 0)
                    {
                        HyperVSocket.Send(response);

                        throw new PSDirectException(
                                  PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidCredential));
                    }

                    //
                    // If PowerShell Direct in VM supports configuration, send configuration name.
                    //
                    if (string.Compare(responseString, "CONF", StringComparison.Ordinal) == 0)
                    {
                        if (emptyConfiguration)
                        {
                            HyperVSocket.Send(Encoding.ASCII.GetBytes("EMPTYCF"));
                        }
                        else
                        {
                            HyperVSocket.Send(Encoding.ASCII.GetBytes("NONEMPTYCF"));
                            HyperVSocket.Receive(response);

                            byte[] configName = Encoding.Unicode.GetBytes(configurationName);
                            HyperVSocket.Send(configName);
                        }
                    }
                    else
                    {
                        HyperVSocket.Send(response);
                    }
                }

                TextReader           = new StreamReader(Stream);
                TextWriter           = new StreamWriter(Stream);
                TextWriter.AutoFlush = true;

                result = true;
            }
            else
            {
                _tracer.WriteMessage("RemoteSessionHyperVSocketClient", "Connect", Guid.Empty,
                                     "Client unable to connect.");

                result = false;
            }

            return(result);
        }
示例#15
0
 public PSRemotingDataStructureException() : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.DefaultRemotingExceptionMessage, new object[] { typeof(PSRemotingDataStructureException).FullName }))
 {
     this.SetDefaultErrorRecord();
 }
        public RemoteSessionHyperVSocketServer(bool LoopbackMode)
        {
            // TODO: uncomment below code when .NET supports Hyper-V socket duplication

            /*
             * NamedPipeClientStream clientPipeStream;
             * byte[] buffer = new byte[1000];
             * int bytesRead;
             */
            _syncObject = new object();

            Exception ex = null;

            try
            {
                // TODO: uncomment below code when .NET supports Hyper-V socket duplication

                /*
                 * if (!LoopbackMode)
                 * {
                 *  //
                 *  // Create named pipe client.
                 *  //
                 *  using (clientPipeStream = new NamedPipeClientStream(".",
                 *                                                      "PS_VMSession",
                 *                                                      PipeDirection.InOut,
                 *                                                      PipeOptions.None,
                 *                                                      TokenImpersonationLevel.None))
                 *  {
                 *      //
                 *      // Connect to named pipe server.
                 *      //
                 *      clientPipeStream.Connect(10*1000);
                 *
                 *      //
                 *      // Read LPWSAPROTOCOL_INFO.
                 *      //
                 *      bytesRead = clientPipeStream.Read(buffer, 0, 1000);
                 *  }
                 * }
                 *
                 * //
                 * // Create duplicate socket.
                 * //
                 * byte[] protocolInfo = new byte[bytesRead];
                 * Array.Copy(buffer, protocolInfo, bytesRead);
                 *
                 * SocketInformation sockInfo = new SocketInformation();
                 * sockInfo.ProtocolInformation = protocolInfo;
                 * sockInfo.Options = SocketInformationOptions.Connected;
                 *
                 * socket = new Socket(sockInfo);
                 * if (socket == null)
                 * {
                 *  Dbg.Assert(false, "Unexpected error in RemoteSessionHyperVSocketServer.");
                 *
                 *  tracer.WriteMessage("RemoteSessionHyperVSocketServer", "RemoteSessionHyperVSocketServer", Guid.Empty,
                 *      "Unexpected error in constructor: {0}", "socket duplication failure");
                 * }
                 */

                // TODO: remove below 6 lines of code when .NET supports Hyper-V socket duplication
                Guid serviceId = new Guid("a5201c21-2770-4c11-a68e-f182edb29220"); // HV_GUID_VM_SESSION_SERVICE_ID_2
                HyperVSocketEndPoint endpoint = new HyperVSocketEndPoint(HyperVSocketEndPoint.AF_HYPERV, Guid.Empty, serviceId);

                Socket listenSocket = new Socket(endpoint.AddressFamily, SocketType.Stream, (System.Net.Sockets.ProtocolType) 1);
                listenSocket.Bind(endpoint);

                listenSocket.Listen(1);
                HyperVSocket = listenSocket.Accept();

                Stream = new NetworkStream(HyperVSocket, true);

                // Create reader/writer streams.
                TextReader           = new StreamReader(Stream);
                TextWriter           = new StreamWriter(Stream);
                TextWriter.AutoFlush = true;

                //
                // listenSocket is not closed when it goes out of scope here. Sometimes it is
                // closed later in this thread, while other times it is not closed at all. This will
                // cause problem when we set up a second PowerShell Direct session. Let's
                // explicitly close listenSocket here for safe.
                //
                if (listenSocket != null)
                {
                    try { listenSocket.Dispose(); }
                    catch (ObjectDisposedException) { }
                }
            }
            catch (Exception e)
            {
                ex = e;
            }

            if (ex != null)
            {
                Dbg.Fail("Unexpected error in RemoteSessionHyperVSocketServer.");

                // Unexpected error.
                string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty;
                _tracer.WriteMessage("RemoteSessionHyperVSocketServer", "RemoteSessionHyperVSocketServer", Guid.Empty,
                                     "Unexpected error in constructor: {0}", errorMessage);

                throw new PSInvalidOperationException(
                          PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemoteSessionHyperVSocketServerConstructorFailure),
                          ex,
                          nameof(PSRemotingErrorId.RemoteSessionHyperVSocketServerConstructorFailure),
                          ErrorCategory.InvalidOperation,
                          null);
            }
        }
示例#17
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();
        }