示例#1
0
 /// <summary>
 /// Creates a new instance of the ConsoleServicePSHost class
 /// with the given IConsoleHost implementation.
 /// </summary>
 /// <param name="hostDetails">
 /// Provides details about the host application.
 /// </param>
 /// <param name="hostSupportsInteractiveSession">
 /// An implementation of IHostSupportsInteractiveSession for runspace management.
 /// </param>
 public ConsoleServicePSHost(
     HostDetails hostDetails,
     IHostSupportsInteractiveSession hostSupportsInteractiveSession)
 {
     this.hostDetails       = hostDetails;
     this.hostUserInterface = new ConsoleServicePSHostUserInterface();
     this.hostSupportsInteractiveSession = hostSupportsInteractiveSession;
 }
        /// <summary>
        /// End Processing
        /// </summary>
        protected override void EndProcessing()
        {
            // Check for host that supports interactive remote sessions.
            _interactiveHost = this.Host as IHostSupportsInteractiveSession;
            if (_interactiveHost == null)
            {
                WriteError(
                    new ErrorRecord(
                        new ArgumentException(RemotingErrorIdStrings.HostDoesNotSupportIASession),
                        "EnterPSHostProcessHostDoesNotSupportIASession",
                        ErrorCategory.InvalidArgument,
                        null));

                return;
            }

            // Check selected process for existence, and whether it hosts PowerShell.
            switch (ParameterSetName)
            {
            case ProcessIdParameterSet:
                Process = GetProcessById(Id);
                break;

            case ProcessNameParameterSet:
                Process = GetProcessByName(Name);
                break;

            case PSHostProcessInfoParameterSet:
                Process = GetProcessByHostProcessInfo(HostProcessInfo);
                break;
            }
            VerifyProcess(Process);

            // Create named pipe runspace for selected process and open.
            Runspace namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);

            // Set runspace prompt.  The runspace is closed on pop so we don't
            // have to reverse this change.
            PrepareRunspace(namedPipeRunspace);

            try
            {
                // Push runspace onto host.
                _interactiveHost.PushRunspace(namedPipeRunspace);
            }
            catch (Exception e)
            {
                CommandProcessorBase.CheckForSevereException(e);
                namedPipeRunspace.Close();

                ThrowTerminatingError(
                    new ErrorRecord(
                        e,
                        "EnterPSHostProcessCannotPushRunspace",
                        ErrorCategory.InvalidOperation,
                        this));
            }
        }
示例#3
0
        /// <summary>
        /// Gets the external host as an IHostSupportsInteractiveSession if it implements this interface;
        /// throws an exception otherwise.
        /// </summary>
        private IHostSupportsInteractiveSession GetIHostSupportsInteractiveSession()
        {
            IHostSupportsInteractiveSession host = _externalHostRef.Value as IHostSupportsInteractiveSession;

            if (host == null)
            {
                throw new PSNotImplementedException();
            }
            return(host);
        }
示例#4
0
        private bool IsRunspacePushed(PSHost host)
        {
            IHostSupportsInteractiveSession session = host as IHostSupportsInteractiveSession;

            if (session == null)
            {
                return(false);
            }
            return(session.IsRunspacePushed);
        }
示例#5
0
        private IHostSupportsInteractiveSession GetIHostSupportsInteractiveSession()
        {
            IHostSupportsInteractiveSession session = this.externalHostRef.Value as IHostSupportsInteractiveSession;

            if (session == null)
            {
                throw new PSNotImplementedException();
            }
            return(session);
        }
 /// <summary>
 /// Creates a new instance of the ConsoleServicePSHost class
 /// with the given IConsoleHost implementation.
 /// </summary>
 /// <param name="powerShellContext">
 /// An implementation of IHostSupportsInteractiveSession for runspace management.
 /// </param>
 /// <param name="hostDetails">
 /// Provides details about the host application.
 /// </param>
 /// <param name="hostUserInterface">
 /// The EditorServicesPSHostUserInterface implementation to use for this host.
 /// </param>
 /// <param name="logger">An ILogger implementation to use for this host.</param>
 public EditorServicesPSHost(
     PowerShellContext powerShellContext,
     HostDetails hostDetails,
     EditorServicesPSHostUserInterface hostUserInterface,
     ILogger logger)
 {
     this.Logger            = logger;
     this.hostDetails       = hostDetails;
     this.hostUserInterface = hostUserInterface;
     this.hostSupportsInteractiveSession = powerShellContext;
 }
示例#7
0
        protected override void StopProcessing()
        {
            IHostSupportsInteractiveSession host = base.Host as IHostSupportsInteractiveSession;

            if (host == null)
            {
                base.WriteError(new ErrorRecord(new ArgumentException(base.GetMessage(RemotingErrorIdStrings.HostDoesNotSupportPushRunspace)), PSRemotingErrorId.HostDoesNotSupportPushRunspace.ToString(), ErrorCategory.InvalidArgument, null));
            }
            else
            {
                host.PopRunspace();
            }
        }
示例#8
0
        private RemoteRunspace GetRemoteRunspaceToClose(PSHost clientHost)
        {
            IHostSupportsInteractiveSession session = clientHost as IHostSupportsInteractiveSession;

            if ((session != null) && session.IsRunspacePushed)
            {
                RemoteRunspace runspace = session.Runspace as RemoteRunspace;
                if ((runspace != null) && runspace.ShouldCloseOnPop)
                {
                    return(runspace);
                }
            }
            return(null);
        }
示例#9
0
        /// <summary>
        /// Process record.
        /// </summary>
        protected override void ProcessRecord()
        {
            // Pop it off the local host.
            IHostSupportsInteractiveSession host = this.Host as IHostSupportsInteractiveSession;

            if (host == null)
            {
                WriteError(
                    new ErrorRecord(
                        new ArgumentException(GetMessage(RemotingErrorIdStrings.HostDoesNotSupportPushRunspace)),
                        nameof(PSRemotingErrorId.HostDoesNotSupportPushRunspace),
                        ErrorCategory.InvalidArgument,
                        null));
                return;
            }

            host.PopRunspace();
        }
示例#10
0
        /// <summary>
        /// Is runspace pushed.
        /// </summary>
        private bool IsRunspacePushed(PSHost host)
        {
            IHostSupportsInteractiveSession host2 = host as IHostSupportsInteractiveSession;

            if (host2 == null)
            {
                return(false);
            }

            // IsRunspacePushed can throw (not implemented exception)
            try
            {
                return(host2.IsRunspacePushed);
            }
            catch (PSNotImplementedException) { }

            return(false);
        }
示例#11
0
        /// <summary>
        /// Get remote runspace to close.
        /// </summary>
        private RemoteRunspace GetRemoteRunspaceToClose(PSHost clientHost)
        {
            // Figure out if we need to close the remote runspace. Return null if we don't.

            // Are we a Start-PSSession enabled host?
            IHostSupportsInteractiveSession host = clientHost as IHostSupportsInteractiveSession;

            if (host == null || !host.IsRunspacePushed)
            {
                return(null);
            }

            // Now inspect the runspace.
            RemoteRunspace remoteRunspace = host.Runspace as RemoteRunspace;

            if (remoteRunspace == null || !remoteRunspace.ShouldCloseOnPop)
            {
                return(null);
            }

            // At this point it is clear we have to close the remote runspace, so return it.
            return(remoteRunspace);
        }
        /// <summary>
        /// End Processing.
        /// </summary>
        protected override void EndProcessing()
        {
            // Check if system is in locked down mode, in which case this cmdlet is disabled.
            if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
            {
                WriteError(
                    new ErrorRecord(
                        new PSSecurityException(RemotingErrorIdStrings.EnterPSHostProcessCmdletDisabled),
                        "EnterPSHostProcessCmdletDisabled",
                        ErrorCategory.SecurityError,
                        null));

                return;
            }

            // Check for host that supports interactive remote sessions.
            _interactiveHost = this.Host as IHostSupportsInteractiveSession;
            if (_interactiveHost == null)
            {
                WriteError(
                    new ErrorRecord(
                        new ArgumentException(RemotingErrorIdStrings.HostDoesNotSupportIASession),
                        "EnterPSHostProcessHostDoesNotSupportIASession",
                        ErrorCategory.InvalidArgument,
                        null));

                return;
            }

            // Check selected process for existence, and whether it hosts PowerShell.
            Runspace namedPipeRunspace = null;

            switch (ParameterSetName)
            {
            case ProcessIdParameterSet:
                Process = GetProcessById(Id);
                VerifyProcess(Process);
                namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);
                break;

            case ProcessNameParameterSet:
                Process = GetProcessByName(Name);
                VerifyProcess(Process);
                namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);
                break;

            case PSHostProcessInfoParameterSet:
                Process = GetProcessByHostProcessInfo(HostProcessInfo);
                VerifyProcess(Process);

                // Create named pipe runspace for selected process and open.
                namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);
                break;

            case PipeNameParameterSet:
                VerifyPipeName(CustomPipeName);
                namedPipeRunspace = CreateNamedPipeRunspace(CustomPipeName);
                break;
            }

            // Set runspace prompt.  The runspace is closed on pop so we don't
            // have to reverse this change.
            PrepareRunspace(namedPipeRunspace);

            try
            {
                // Push runspace onto host.
                _interactiveHost.PushRunspace(namedPipeRunspace);
            }
            catch (Exception e)
            {
                namedPipeRunspace.Close();

                ThrowTerminatingError(
                    new ErrorRecord(
                        e,
                        "EnterPSHostProcessCannotPushRunspace",
                        ErrorCategory.InvalidOperation,
                        this));
            }
        }
示例#13
0
        /// <summary>
        /// Called by the engine to notify the host that a runspace pop has been requested.
        /// </summary>
        /// <seealso cref="PushRunspace"/>
        public void PopRunspace()
        {
            IHostSupportsInteractiveSession host = GetIHostSupportsInteractiveSession();

            host.PopRunspace();
        }
示例#14
0
        /// <summary>
        /// Called by the engine to notify the host that a runspace push has been requested.
        /// </summary>
        /// <seealso cref="PopRunspace"/>
        public void PushRunspace(System.Management.Automation.Runspaces.Runspace runspace)
        {
            IHostSupportsInteractiveSession host = GetIHostSupportsInteractiveSession();

            host.PushRunspace(runspace);
        }
示例#15
0
        protected override void ProcessRecord()
        {
            IHostSupportsInteractiveSession session = base.Host as IHostSupportsInteractiveSession;

            if (session == null)
            {
                base.WriteError(new ErrorRecord(new ArgumentException(base.GetMessage(RemotingErrorIdStrings.HostDoesNotSupportPushRunspace)), PSRemotingErrorId.HostDoesNotSupportPushRunspace.ToString(), ErrorCategory.InvalidArgument, null));
            }

            /*
             * else if (((base.Context != null) && (base.Context.EngineHostInterface != null)) && ((base.Context.EngineHostInterface.ExternalHost != null) && (base.Context.EngineHostInterface.ExternalHost is ServerRemoteHost)))
             * {
             * base.WriteError(new ErrorRecord(new ArgumentException(base.GetMessage(RemotingErrorIdStrings.RemoteHostDoesNotSupportPushRunspace)), PSRemotingErrorId.RemoteHostDoesNotSupportPushRunspace.ToString(), ErrorCategory.InvalidArgument, null));
             * }
             */
            else
            {
                InternalHost targetObject = base.Host as InternalHost;
                if ((targetObject != null) && targetObject.HostInNestedPrompt())
                {
                    base.ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.HostInNestedPrompt, new object[0])), "HostInNestedPrompt", ErrorCategory.InvalidOperation, targetObject));
                }
                RemoteRunspace runspaceMatchingRunspaceId = null;
                string         parameterSetName           = base.ParameterSetName;
                if (parameterSetName != null)
                {
                    if (!(parameterSetName == "ComputerName"))
                    {
                        if (parameterSetName == "Uri")
                        {
                            runspaceMatchingRunspaceId = this.CreateRunspaceWhenUriParameterSpecified();
                        }
                        else if (parameterSetName == "Session")
                        {
                            runspaceMatchingRunspaceId = (RemoteRunspace)this.remoteRunspaceInfo.Runspace;
                        }
                        else if (parameterSetName == "InstanceId")
                        {
                            runspaceMatchingRunspaceId = this.GetRunspaceMatchingRunspaceId(this.InstanceId);
                        }
                        else if (parameterSetName == "Id")
                        {
                            runspaceMatchingRunspaceId = this.GetRunspaceMatchingSessionId(this.Id);
                        }
                        else if (parameterSetName == "Name")
                        {
                            runspaceMatchingRunspaceId = this.GetRunspaceMatchingName(this.Name);
                        }
                    }
                    else
                    {
                        runspaceMatchingRunspaceId = this.CreateRunspaceWhenComputerNameParameterSpecified();
                    }
                }
                if (runspaceMatchingRunspaceId != null)
                {
                    if (runspaceMatchingRunspaceId.RunspaceStateInfo.State == RunspaceState.Disconnected)
                    {
                        if (!runspaceMatchingRunspaceId.CanConnect)
                        {
                            string message = StringUtil.Format(RemotingErrorIdStrings.SessionNotAvailableForConnection, new object[0]);
                            base.WriteError(new ErrorRecord(new RuntimeException(message), "EnterPSSessionCannotConnectDisconnectedSession", ErrorCategory.InvalidOperation, runspaceMatchingRunspaceId));
                            return;
                        }
                        Exception innerException = null;
                        try
                        {
                            runspaceMatchingRunspaceId.Connect();
                        }
                        catch (PSRemotingTransportException exception2)
                        {
                            innerException = exception2;
                        }
                        catch (PSInvalidOperationException exception3)
                        {
                            innerException = exception3;
                        }
                        catch (InvalidRunspacePoolStateException exception4)
                        {
                            innerException = exception4;
                        }
                        if (innerException != null)
                        {
                            string str2 = StringUtil.Format(RemotingErrorIdStrings.SessionConnectFailed, new object[0]);
                            base.WriteError(new ErrorRecord(new RuntimeException(str2, innerException), "EnterPSSessionConnectSessionFailed", ErrorCategory.InvalidOperation, runspaceMatchingRunspaceId));
                            return;
                        }
                        if (runspaceMatchingRunspaceId.RunspaceAvailability == RunspaceAvailability.Busy)
                        {
                            string str3 = StringUtil.Format(RemotingErrorIdStrings.EnterPSSessionDisconnected, runspaceMatchingRunspaceId.Name);
                            base.WriteError(new ErrorRecord(new RuntimeException(str3, innerException), "EnterPSSessionConnectSessionNotAvailable", ErrorCategory.InvalidOperation, this.remoteRunspaceInfo));
                            runspaceMatchingRunspaceId.DisconnectAsync();
                            return;
                        }
                    }
                    if (runspaceMatchingRunspaceId.RunspaceStateInfo.State != RunspaceState.Opened)
                    {
                        if (base.ParameterSetName == "Session")
                        {
                            string str4 = (this.remoteRunspaceInfo != null) ? this.remoteRunspaceInfo.Name : string.Empty;
                            base.WriteError(new ErrorRecord(new ArgumentException(base.GetMessage(RemotingErrorIdStrings.EnterPSSessionBrokenSession, new object[] { str4, runspaceMatchingRunspaceId.ConnectionInfo.ComputerName, runspaceMatchingRunspaceId.InstanceId })), PSRemotingErrorId.PushedRunspaceMustBeOpen.ToString(), ErrorCategory.InvalidArgument, null));
                        }
                        else
                        {
                            base.WriteError(new ErrorRecord(new ArgumentException(base.GetMessage(RemotingErrorIdStrings.PushedRunspaceMustBeOpen)), PSRemotingErrorId.PushedRunspaceMustBeOpen.ToString(), ErrorCategory.InvalidArgument, null));
                        }
                    }
                    else
                    {
                        if (runspaceMatchingRunspaceId.RunspaceAvailability != RunspaceAvailability.Available)
                        {
                            base.WriteWarning(base.GetMessage(RunspaceStrings.RunspaceNotReady));
                        }
                        try
                        {
                            session.PushRunspace(runspaceMatchingRunspaceId);
                        }
                        catch (Exception)
                        {
                            if ((runspaceMatchingRunspaceId != null) && runspaceMatchingRunspaceId.ShouldCloseOnPop)
                            {
                                runspaceMatchingRunspaceId.Close();
                            }
                            throw;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// End Processing
        /// </summary>
        protected override void EndProcessing()
        {
            // Check for host that supports interactive remote sessions.
            _interactiveHost = this.Host as IHostSupportsInteractiveSession;
            if (_interactiveHost == null)
            {
                WriteError(
                    new ErrorRecord(
                        new ArgumentException(RemotingErrorIdStrings.HostDoesNotSupportIASession),
                        "EnterPSHostProcessHostDoesNotSupportIASession",
                        ErrorCategory.InvalidArgument,
                        null));

                return;
            }

            // Check selected process for existence, and whether it hosts PowerShell.
            switch (ParameterSetName)
            {
                case ProcessIdParameterSet:
                    Process = GetProcessById(Id);
                    break;

                case ProcessNameParameterSet:
                    Process = GetProcessByName(Name);
                    break;

                case PSHostProcessInfoParameterSet:
                    Process = GetProcessByHostProcessInfo(HostProcessInfo);
                    break;
            }
            VerifyProcess(Process);

            // Create named pipe runspace for selected process and open.
            Runspace namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);

            // Set runspace prompt.  The runspace is closed on pop so we don't 
            // have to reverse this change.
            PrepareRunspace(namedPipeRunspace);

            try
            {
                // Push runspace onto host.
                _interactiveHost.PushRunspace(namedPipeRunspace);
            }
            catch (Exception e)
            {
                CommandProcessorBase.CheckForSevereException(e);
                namedPipeRunspace.Close();

                ThrowTerminatingError(
                    new ErrorRecord(
                        e,
                        "EnterPSHostProcessCannotPushRunspace",
                        ErrorCategory.InvalidOperation,
                        this));
            }
        }