コード例 #1
0
ファイル: RunspaceRef.cs プロジェクト: mohsensaaki/PowerShell
        /// <summary>
        /// Parse ps command using script block.
        /// </summary>
        private PSCommand ParsePsCommandUsingScriptBlock(string line, bool?useLocalScope)
        {
            try
            {
                // Extract execution context from local runspace.
                Runspace         localRunspace = _runspaceRef.OldValue;
                ExecutionContext context       = localRunspace.ExecutionContext;

                // This is trusted input as long as we're in FullLanguage mode
                // and if we are not in a loopback configuration mode, in which case we always force remote script commands
                // to be parsed and evaluated on the remote session (not in the current local session).
                RemoteRunspace remoteRunspace       = _runspaceRef.Value as RemoteRunspace;
                bool           isConfiguredLoopback = (remoteRunspace != null) ? remoteRunspace.IsConfiguredLoopBack : false;
                bool           isTrustedInput       = !isConfiguredLoopback && (localRunspace.ExecutionContext.LanguageMode == PSLanguageMode.FullLanguage);

                // Create PowerShell from ScriptBlock.
                ScriptBlock scriptBlock = ScriptBlock.Create(context, line);
                PowerShell  powerShell  = scriptBlock.GetPowerShell(context, isTrustedInput, useLocalScope, null);
                return(powerShell.Commands);
            }
            catch (ScriptBlockToPowerShellNotSupportedException)
            {
            }
            catch (RuntimeException)
            {
            }

            // If parsing failed return null.
            return(null);
        }
コード例 #2
0
        /// <summary>
        /// Push runspace to use for remote command execution.
        /// </summary>
        /// <param name="runspace">RemoteRunspace.</param>
        public override void PushRunspace(Runspace runspace)
        {
            if (_debugger == null)
            {
                throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostNoDebuggerToPush);
            }

            if (_pushedRunspace != null)
            {
                throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostAlreadyPushed);
            }

            if (!(runspace is RemoteRunspace remoteRunspace))
            {
                throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostNotRemoteRunspace);
            }

            // PSEdit support.  Existence of RemoteSessionOpenFileEvent event indicates host supports PSEdit
            _hostSupportsPSEdit = false;
            PSEventManager localEventManager = Runspace?.Events;

            _hostSupportsPSEdit = (localEventManager != null) ? localEventManager.GetEventSubscribers(HostUtilities.RemoteSessionOpenFileEvent).GetEnumerator().MoveNext() : false;
            if (_hostSupportsPSEdit)
            {
                AddPSEditForRunspace(remoteRunspace);
            }

            _debugger.PushDebugger(runspace.Debugger);
            _pushedRunspace = remoteRunspace;
        }
コード例 #3
0
ファイル: PSSession.cs プロジェクト: modulexcite/pash-1
        internal PSSession(RemoteRunspace remoteRunspace)
        {
            this.remoteRunspace = remoteRunspace;
            if (remoteRunspace.Id != -1)
            {
                this.sessionid = remoteRunspace.Id;
            }
            else
            {
                this.sessionid    = Interlocked.Increment(ref seed);
                remoteRunspace.Id = this.sessionid;
            }
            if (!string.IsNullOrEmpty(remoteRunspace.Name))
            {
                this.name = remoteRunspace.Name;
            }
            else
            {
                this.name           = this.AutoGenerateRunspaceName();
                remoteRunspace.Name = this.name;
            }
            string shell = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <string>(remoteRunspace.ConnectionInfo, "ShellUri", string.Empty);

            this.shell = this.GetDisplayShellName(shell);
        }
コード例 #4
0
 internal ExecutionCmdletHelperComputerName(RemoteRunspace remoteRunspace, Pipeline pipeline)
 {
     this.remoteRunspace          = remoteRunspace;
     remoteRunspace.StateChanged += new EventHandler <RunspaceStateEventArgs>(this.HandleRunspaceStateChanged);
     this.pipeline          = pipeline;
     pipeline.StateChanged += new EventHandler <PipelineStateEventArgs>(this.HandlePipelineStateChanged);
 }
コード例 #5
0
        private void RemovePSEditFromRunspace(RemoteRunspace remoteRunspace)
        {
            if (remoteRunspace.Events == null)
            {
                return;
            }

            // It is possible for the popped runspace to be in a bad state after an error.
            if ((remoteRunspace.RunspaceStateInfo.State != RunspaceState.Opened) || (remoteRunspace.RunspaceAvailability != RunspaceAvailability.Available))
            {
                return;
            }

            // Remove event handler.
            remoteRunspace.Events.ReceivedEvents.PSEventReceived -= HandleRemoteSessionForwardedEvent;

            // Remove script function.
            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.Runspace = remoteRunspace;
                powershell.AddScript(HostUtilities.RemovePSEditFunction);
                try
                {
                    powershell.Invoke();
                }
                catch (RemoteException) { }
            }
        }
コード例 #6
0
        private RemoteRunspace CreateRunspaceWhenComputerNameParameterSpecified()
        {
            RemoteRunspace runspace     = null;
            string         computerName = base.ResolveComputerName(this.computerName);

            try
            {
                WSManConnectionInfo connectionInfo = new WSManConnectionInfo(this.UseSSL.IsPresent, computerName, this.Port, this.ApplicationName, this.ConfigurationName, this.Credential)
                {
                    AuthenticationMechanism = this.Authentication
                };
                base.UpdateConnectionInfo(connectionInfo);
                connectionInfo.EnableNetworkAccess = (bool)this.EnableNetworkAccess;
                runspace = this.CreateTemporaryRemoteRunspace(base.Host, connectionInfo);
            }
            catch (InvalidOperationException exception)
            {
                this.WriteErrorCreateRemoteRunspaceFailed(exception, computerName);
            }
            catch (ArgumentException exception2)
            {
                this.WriteErrorCreateRemoteRunspaceFailed(exception2, computerName);
            }
            catch (PSRemotingTransportException exception3)
            {
                this.WriteErrorCreateRemoteRunspaceFailed(exception3, computerName);
            }
            return(runspace);
        }
コード例 #7
0
        private RemoteRunspace CreateTemporaryRemoteRunspace(PSHost host, WSManConnectionInfo connectionInfo)
        {
            int            num;
            string         name     = PSSession.GenerateRunspaceName(out num);
            RemoteRunspace runspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, host, this.SessionOption.ApplicationArguments, name, num);

            runspace.URIRedirectionReported += new EventHandler <RemoteDataEventArgs <Uri> >(this.HandleURIDirectionReported);
            this.stream = new ObjectStream();
            try
            {
                runspace.Open();
                runspace.ShouldCloseOnPop = true;
            }
            finally
            {
                runspace.URIRedirectionReported -= new EventHandler <RemoteDataEventArgs <Uri> >(this.HandleURIDirectionReported);
                this.stream.ObjectWriter.Close();
                if (runspace.RunspaceStateInfo.State != RunspaceState.Opened)
                {
                    runspace.Dispose();
                    runspace = null;
                }
            }
            return(runspace);
        }
コード例 #8
0
        } // CoreBeginProcessing

        /// <summary>
        /// Create a throttle operation using NewProcessConnectionInfo
        /// ie., Out-Of-Process runspace.
        /// </summary>
        protected override void CreateHelpersForSpecifiedComputerNames()
        {
            // If we're in ConstrainedLanguage mode and the system is in lockdown mode,
            // ensure that they haven't specified a ScriptBlock or InitScript - as
            // we can't protect that boundary
            if ((Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) &&
                (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce) &&
                ((ScriptBlock != null) || (InitializationScript != null)))
            {
                ThrowTerminatingError(
                    new ErrorRecord(
                        new PSNotSupportedException(RemotingErrorIdStrings.CannotStartJobInconsistentLanguageMode),
                            "CannotStartJobInconsistentLanguageMode",
                            ErrorCategory.PermissionDenied,
                            Context.LanguageMode));
            }

            NewProcessConnectionInfo connectionInfo = new NewProcessConnectionInfo(this.Credential);
            connectionInfo.RunAs32 = _shouldRunAs32;
            connectionInfo.InitializationScript = _initScript;
            connectionInfo.AuthenticationMechanism = this.Authentication;
            connectionInfo.PSVersion = this.PSVersion;

            RemoteRunspace remoteRunspace = (RemoteRunspace)RunspaceFactory.CreateRunspace(connectionInfo, this.Host,
                        Utils.GetTypeTableFromExecutionContextTLS());

            remoteRunspace.Events.ReceivedEvents.PSEventReceived += OnRunspacePSEventReceived;

            Pipeline pipeline = CreatePipeline(remoteRunspace);

            IThrottleOperation operation =
                new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline);

            Operations.Add(operation);
        }
コード例 #9
0
        /// <summary>
        /// This constructor will be used to created a remote runspace info
        /// object with a auto generated name.
        /// </summary>
        /// <param name="remoteRunspace">Remote runspace object for which
        /// the info object need to be created</param>
        internal PSSession(RemoteRunspace remoteRunspace)
        {
            _remoteRunspace = remoteRunspace;

            // Use passed in session Id, if available.
            if (remoteRunspace.PSSessionId != -1)
            {
                Id = remoteRunspace.PSSessionId;
            }
            else
            {
                Id = System.Threading.Interlocked.Increment(ref s_seed);
                remoteRunspace.PSSessionId = Id;
            }

            // Use passed in friendly name, if available.
            if (!string.IsNullOrEmpty(remoteRunspace.PSSessionName))
            {
                Name = remoteRunspace.PSSessionName;
            }
            else
            {
                Name = "Runspace" + Id;
                remoteRunspace.PSSessionName = Name;
            }

            switch (remoteRunspace.ConnectionInfo)
            {
            case WSManConnectionInfo _:
                ComputerType = TargetMachineType.RemoteMachine;
                string fullShellName = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <string>(
                    remoteRunspace.ConnectionInfo,
                    "ShellUri", string.Empty);
                ConfigurationName = GetDisplayShellName(fullShellName);
                break;

            case VMConnectionInfo vmConnectionInfo:
                ComputerType      = TargetMachineType.VirtualMachine;
                ConfigurationName = vmConnectionInfo.ConfigurationName;
                break;

            case ContainerConnectionInfo containerConnectionInfo:
                ComputerType      = TargetMachineType.Container;
                ConfigurationName = containerConnectionInfo.ContainerProc.ConfigurationName;
                break;

            case SSHConnectionInfo _:
                ComputerType      = TargetMachineType.RemoteMachine;
                ConfigurationName = "DefaultShell";
                break;

            case NewProcessConnectionInfo _:
                ComputerType = TargetMachineType.RemoteMachine;
                break;

            default:
                Dbg.Assert(false, "Invalid Runspace");
                break;
            }
        }
コード例 #10
0
        private PSRemotingJob FindJobForSession(PSSession session)
        {
            PSRemotingJob  job      = null;
            RemoteRunspace runspace = session.Runspace as RemoteRunspace;

            if ((runspace == null) || (runspace.RemoteCommand != null))
            {
                return(null);
            }
            foreach (Job job2 in base.JobRepository.Jobs)
            {
                if (!(job2 is PSRemotingJob))
                {
                    continue;
                }
                foreach (PSRemotingChildJob job3 in job2.ChildJobs)
                {
                    if (job3.Runspace.InstanceId.Equals(session.InstanceId) && (job3.JobStateInfo.State == JobState.Disconnected))
                    {
                        job = (PSRemotingJob)job2;
                        break;
                    }
                }
                if (job != null)
                {
                    return(job);
                }
            }
            return(job);
        }
コード例 #11
0
ファイル: Runspace.cs プロジェクト: modulexcite/pash-1
        protected void UpdateRunspaceAvailability(RunspaceState runspaceState, bool raiseEvent)
        {
            System.Management.Automation.Runspaces.RunspaceAvailability runspaceAvailability = this.RunspaceAvailability;
            RemoteRunspace     runspace = this as RemoteRunspace;
            ConnectCommandInfo info     = (runspace != null) ? runspace.RemoteCommand : null;

            switch (runspaceAvailability)
            {
            case System.Management.Automation.Runspaces.RunspaceAvailability.None:
                if (runspaceState == RunspaceState.Opened)
                {
                    this.RunspaceAvailability = ((info == null) && (this.GetCurrentlyRunningPipeline() == null)) ? System.Management.Automation.Runspaces.RunspaceAvailability.Available : System.Management.Automation.Runspaces.RunspaceAvailability.Busy;
                }
                break;

            case System.Management.Automation.Runspaces.RunspaceAvailability.Available:
            case System.Management.Automation.Runspaces.RunspaceAvailability.AvailableForNestedCommand:
            case System.Management.Automation.Runspaces.RunspaceAvailability.Busy:
                switch (runspaceState)
                {
                case RunspaceState.Closed:
                case RunspaceState.Closing:
                case RunspaceState.Broken:
                case RunspaceState.Disconnected:
                    this.RunspaceAvailability = System.Management.Automation.Runspaces.RunspaceAvailability.None;
                    goto Label_007D;
                }
                break;
            }
Label_007D:
            if (raiseEvent && (this.RunspaceAvailability != runspaceAvailability))
            {
                this.OnAvailabilityChanged(new RunspaceAvailabilityEventArgs(this.RunspaceAvailability));
            }
        }
コード例 #12
0
ファイル: RemoteHost.cs プロジェクト: jsdiggs13/PowerShell
        /// <summary>
        /// Execute void method.
        /// </summary>
        internal void ExecuteVoidMethod(PSHost clientHost)
        {
            // The clientHost can be null if the user creates a runspace object without providing
            // a host parameter.
            if (clientHost == null)
            {
                return;
            }

            RemoteRunspace remoteRunspaceToClose = null;

            if (this.IsSetShouldExitOrPopRunspace)
            {
                remoteRunspaceToClose = GetRemoteRunspaceToClose(clientHost);
            }

            try
            {
                object targetObject = this.SelectTargetObject(clientHost);
                MyMethodBase.Invoke(targetObject, Parameters);
            }
            finally
            {
                if (remoteRunspaceToClose != null)
                {
                    remoteRunspaceToClose.Close();
                }
            }
        }
コード例 #13
0
        private List <RemoteRunspace> CreateRunspacesWhenRunspaceParameterSpecified()
        {
            List <RemoteRunspace> list = new List <RemoteRunspace>();

            base.ValidateRemoteRunspacesSpecified();
            int rsIndex = 0;

            foreach (PSSession session in this.remoteRunspaceInfos)
            {
                if ((session == null) || (session.Runspace == null))
                {
                    base.ThrowTerminatingError(new ErrorRecord(new ArgumentNullException("PSSession"), "PSSessionArgumentNull", ErrorCategory.InvalidArgument, null));
                }
                else
                {
                    try
                    {
                        int                 num2;
                        RemoteRunspace      runspace       = (RemoteRunspace)session.Runspace;
                        WSManConnectionInfo connectionInfo = runspace.ConnectionInfo as WSManConnectionInfo;
                        WSManConnectionInfo info2          = null;
                        if (connectionInfo != null)
                        {
                            info2 = connectionInfo.Copy();
                            info2.EnableNetworkAccess = info2.EnableNetworkAccess || (this.EnableNetworkAccess != false);
                        }
                        else
                        {
                            Uri    uri      = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <Uri>(runspace.ConnectionInfo, "ConnectionUri", null);
                            string shellUri = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <string>(runspace.ConnectionInfo, "ShellUri", string.Empty);
                            info2 = new WSManConnectionInfo(uri, shellUri, runspace.ConnectionInfo.Credential);
                            base.UpdateConnectionInfo(info2);
                            info2.EnableNetworkAccess = (bool)this.EnableNetworkAccess;
                        }
                        RemoteRunspacePoolInternal remoteRunspacePoolInternal = runspace.RunspacePool.RemoteRunspacePoolInternal;
                        TypeTable typeTable = null;
                        if (((remoteRunspacePoolInternal != null) && (remoteRunspacePoolInternal.DataStructureHandler != null)) && (remoteRunspacePoolInternal.DataStructureHandler.TransportManager != null))
                        {
                            typeTable = remoteRunspacePoolInternal.DataStructureHandler.TransportManager.Fragmentor.TypeTable;
                        }
                        string         runspaceName = this.GetRunspaceName(rsIndex, out num2);
                        RemoteRunspace item         = new RemoteRunspace(typeTable, info2, base.Host, this.SessionOption.ApplicationArguments, runspaceName, num2);
                        list.Add(item);
                    }
                    catch (UriFormatException exception)
                    {
                        PipelineWriter  objectWriter = this.stream.ObjectWriter;
                        ErrorRecord     errorRecord  = new ErrorRecord(exception, "CreateRemoteRunspaceFailed", ErrorCategory.InvalidArgument, session);
                        Action <Cmdlet> action       = delegate(Cmdlet cmdlet) {
                            cmdlet.WriteError(errorRecord);
                        };
                        objectWriter.Write(action);
                    }
                }
                rsIndex++;
            }
            return(list);
        }
コード例 #14
0
        private Runspace CreateNamedPipeRunspace(NamedPipeConnectionInfo connectionInfo)
        {
            TypeTable      typeTable      = TypeTable.LoadDefaultTypeFiles();
            RemoteRunspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo, this.Host, typeTable) as RemoteRunspace;

            remoteRunspace.Name             = NamedPipeRunspaceName;
            remoteRunspace.ShouldCloseOnPop = true;
            _connectingRemoteRunspace       = remoteRunspace;

            try
            {
                remoteRunspace.Open();
                remoteRunspace.Debugger?.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript);
            }
            catch (RuntimeException e)
            {
                // Unwrap inner exception for original error message, if any.
                string errorMessage = (e.InnerException != null) ? (e.InnerException.Message ?? string.Empty) : string.Empty;

                if (connectionInfo.CustomPipeName != null)
                {
                    ThrowTerminatingError(
                        new ErrorRecord(
                            new RuntimeException(
                                StringUtil.Format(
                                    RemotingErrorIdStrings.EnterPSHostProcessCannotConnectToPipe,
                                    connectionInfo.CustomPipeName,
                                    errorMessage),
                                e.InnerException),
                            "EnterPSHostProcessCannotConnectToPipe",
                            ErrorCategory.OperationTimeout,
                            this));
                }
                else
                {
                    string msgAppDomainName = connectionInfo.AppDomainName ?? NamedPipeUtils.DefaultAppDomainName;

                    ThrowTerminatingError(
                        new ErrorRecord(
                            new RuntimeException(
                                StringUtil.Format(
                                    RemotingErrorIdStrings.EnterPSHostProcessCannotConnectToProcess,
                                    msgAppDomainName,
                                    connectionInfo.ProcessId,
                                    errorMessage),
                                e.InnerException),
                            "EnterPSHostProcessCannotConnectToProcess",
                            ErrorCategory.OperationTimeout,
                            this));
                }
            }
            finally
            {
                _connectingRemoteRunspace = null;
            }

            return(remoteRunspace);
        }
コード例 #15
0
ファイル: RunspaceRef.cs プロジェクト: modulexcite/pash-1
        private void WriteRCFailedError()
        {
            RemoteRunspace runspace = this._runspaceRef.Value as RemoteRunspace;

            if ((runspace != null) && (runspace.RunspacePool.RemoteRunspacePoolInternal.Host != null))
            {
                runspace.RunspacePool.RemoteRunspacePoolInternal.Host.UI.WriteErrorLine(StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnectingError, runspace.ConnectionInfo.ComputerName));
            }
        }
コード例 #16
0
ファイル: RunspaceRef.cs プロジェクト: modulexcite/pash-1
        private void StartProgressBar(long sourceId, string computerName, int totalSeconds)
        {
            RemoteRunspace runspace = this._runspaceRef.Value as RemoteRunspace;

            if (runspace != null)
            {
                RCProgress.StartProgress(sourceId, computerName, totalSeconds, runspace.RunspacePool.RemoteRunspacePoolInternal.Host);
            }
        }
コード例 #17
0
        /// <summary>
        /// Stop Processing.
        /// </summary>
        protected override void StopProcessing()
        {
            RemoteRunspace connectingRunspace = _connectingRemoteRunspace;

            if (connectingRunspace != null)
            {
                connectingRunspace.AbortOpen();
            }
        }
コード例 #18
0
ファイル: PSSession.cs プロジェクト: modulexcite/pash-1
 internal bool InsertRunspace(RemoteRunspace remoteRunspace)
 {
     if ((remoteRunspace == null) || (remoteRunspace.InstanceId != this.remoteRunspace.InstanceId))
     {
         return(false);
     }
     this.remoteRunspace = remoteRunspace;
     return(true);
 }
コード例 #19
0
ファイル: RunspaceRef.cs プロジェクト: modulexcite/pash-1
        internal Pipeline CreatePipeline(string line, bool addToHistory, bool useNestedPipelines)
        {
            Pipeline pipeline = null;
            EventHandler <DataAddedEventArgs> handler = null;

            if (this.IsRunspaceOverridden)
            {
                if (((this._runspaceRef.Value is RemoteRunspace) && !string.IsNullOrEmpty(line)) && string.Equals(line.Trim(), "exit", StringComparison.OrdinalIgnoreCase))
                {
                    line = "Exit-PSSession";
                }
                PSCommand command = this.ParsePsCommandUsingScriptBlock(line, null);
                if (command != null)
                {
                    pipeline = useNestedPipelines ? this._runspaceRef.Value.CreateNestedPipeline(command.Commands[0].CommandText, addToHistory) : this._runspaceRef.Value.CreatePipeline(command.Commands[0].CommandText, addToHistory);
                    pipeline.Commands.Clear();
                    foreach (Command command2 in command.Commands)
                    {
                        pipeline.Commands.Add(command2);
                    }
                }
            }
            if (pipeline == null)
            {
                pipeline = useNestedPipelines ? this._runspaceRef.Value.CreateNestedPipeline(line, addToHistory) : this._runspaceRef.Value.CreatePipeline(line, addToHistory);
            }
            RemotePipeline pipeline2 = pipeline as RemotePipeline;

            if (this.IsRunspaceOverridden && (pipeline2 != null))
            {
                PowerShell powerShell = pipeline2.PowerShell;
                if (powerShell.RemotePowerShell != null)
                {
                    powerShell.RemotePowerShell.RCConnectionNotification += new EventHandler <PSConnectionRetryStatusEventArgs>(this.HandleRCConnectionNotification);
                }
                if (handler == null)
                {
                    handler = delegate(object sender, DataAddedEventArgs eventArgs) {
                        RemoteRunspace runspace = this._runspaceRef.Value as RemoteRunspace;
                        PSDataCollection <ErrorRecord> datas = sender as PSDataCollection <ErrorRecord>;
                        if (((runspace != null) && (datas != null)) && (runspace.RunspacePool.RemoteRunspacePoolInternal.Host != null))
                        {
                            foreach (ErrorRecord record in datas.ReadAll())
                            {
                                runspace.RunspacePool.RemoteRunspacePoolInternal.Host.UI.WriteErrorLine(record.ToString());
                            }
                        }
                    };
                }
                powerShell.ErrorBuffer.DataAdded += handler;
            }
            pipeline.SetHistoryString(line);
            return(pipeline);
        }
コード例 #20
0
ファイル: RunspaceRef.cs プロジェクト: modulexcite/pash-1
        internal void Override(RemoteRunspace remoteRunspace, object syncObject, out bool isRunspacePushed)
        {
            lock (this._localSyncObject)
            {
                this._stopInvoke = false;
            }
            try
            {
                if (syncObject != null)
                {
                    lock (syncObject)
                    {
                        this._runspaceRef.Override(remoteRunspace);
                        isRunspacePushed = true;
                        goto Label_0063;
                    }
                }
                this._runspaceRef.Override(remoteRunspace);
                isRunspacePushed = true;
Label_0063:
                using (PowerShell shell = PowerShell.Create())
                {
                    shell.AddCommand("Get-Command");
                    shell.AddParameter("Name", new string[] { "Out-Default", "Exit-PSSession" });
                    shell.Runspace = this._runspaceRef.Value;
                    bool flag2 = this._runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersionWin7RC;
                    shell.IsGetCommandMetadataSpecialPipeline = !flag2;
                    int num = flag2 ? 2 : 3;
                    shell.RemotePowerShell.HostCallReceived += new EventHandler <RemoteDataEventArgs <RemoteHostCall> >(this.HandleHostCall);
                    IAsyncResult asyncResult          = shell.BeginInvoke();
                    PSDataCollection <PSObject> datas = new PSDataCollection <PSObject>();
                    while (!this._stopInvoke)
                    {
                        asyncResult.AsyncWaitHandle.WaitOne(0x3e8);
                        if (asyncResult.IsCompleted)
                        {
                            datas = shell.EndInvoke(asyncResult);
                            break;
                        }
                    }
                    if ((shell.Streams.Error.Count > 0) || (datas.Count < num))
                    {
                        throw RemoteHostExceptions.NewRemoteRunspaceDoesNotSupportPushRunspaceException();
                    }
                    return;
                }
            }
            catch (Exception)
            {
                this._runspaceRef.Revert();
                isRunspacePushed = false;
                throw;
            }
        }
コード例 #21
0
        /// <summary>
        /// Internal method to insert a runspace into a PSSession object.
        /// This is used only for Disconnect/Reconnect scenarios where the
        /// new runspace is a reconstructed runspace having the same Guid
        /// as the existing runspace.
        /// </summary>
        /// <param name="remoteRunspace">Runspace to insert.</param>
        /// <returns>Boolean indicating if runspace was inserted.</returns>
        internal bool InsertRunspace(RemoteRunspace remoteRunspace)
        {
            if (remoteRunspace == null ||
                remoteRunspace.InstanceId != _remoteRunspace.InstanceId)
            {
                return(false);
            }

            _remoteRunspace = remoteRunspace;
            return(true);
        }
コード例 #22
0
        private List <PSSession> GetDisconnectedSessions(PSInvokeExpressionSyncJob job)
        {
            List <PSSession> list = new List <PSSession>();

            foreach (PowerShell shell in job.GetPowerShells())
            {
                string             cmdStr       = ((shell.Commands != null) && (shell.Commands.Commands.Count > 0)) ? shell.Commands.Commands[0].CommandText : string.Empty;
                ConnectCommandInfo info         = new ConnectCommandInfo(shell.InstanceId, cmdStr);
                RunspacePool       runspacePool = null;
                if (shell.RunspacePool != null)
                {
                    runspacePool = shell.RunspacePool;
                }
                else
                {
                    object       runspaceConnection = shell.GetRunspaceConnection();
                    RunspacePool pool2 = runspaceConnection as RunspacePool;
                    if (pool2 != null)
                    {
                        runspacePool = pool2;
                    }
                    else
                    {
                        RemoteRunspace runspace = runspaceConnection as RemoteRunspace;
                        if (runspace != null)
                        {
                            runspacePool = runspace.RunspacePool;
                        }
                    }
                }
                if (runspacePool != null)
                {
                    if (runspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Disconnected)
                    {
                        if (!base.InvokeAndDisconnect || (runspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Opened))
                        {
                            continue;
                        }
                        runspacePool.Disconnect();
                    }
                    string name = runspacePool.RemoteRunspacePoolInternal.Name;
                    if (string.IsNullOrEmpty(name))
                    {
                        int num;
                        name = PSSession.GenerateRunspaceName(out num);
                    }
                    RunspacePool   pool3          = new RunspacePool(true, runspacePool.RemoteRunspacePoolInternal.InstanceId, name, new ConnectCommandInfo[] { info }, runspacePool.RemoteRunspacePoolInternal.ConnectionInfo, base.Host, base.Context.TypeTable);
                    RemoteRunspace remoteRunspace = new RemoteRunspace(pool3);
                    list.Add(new PSSession(remoteRunspace));
                }
            }
            return(list);
        }
コード例 #23
0
        internal Pipeline CreatePipeline(RemoteRunspace remoteRunspace)
        {
            PowerShell shell    = remoteRunspace.GetCapabilities().Equals(RunspaceCapability.Default) ? this.GetPowerShellForPSv2() : this.GetPowerShellForPSv3();
            Pipeline   pipeline = remoteRunspace.CreatePipeline(shell.Commands.Commands[0].CommandText, true);

            pipeline.Commands.Clear();
            foreach (Command command in shell.Commands.Commands)
            {
                pipeline.Commands.Add(command);
            }
            pipeline.RedirectShellErrorOutputPipe = true;
            return(pipeline);
        }
コード例 #24
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);
        }
コード例 #25
0
        private List <RemoteRunspace> CreateRunspacesWhenComputerNameParameterSpecified()
        {
            string[] strArray;
            List <RemoteRunspace> list = new List <RemoteRunspace>();

            base.ResolveComputerNames(this.ComputerName, out strArray);
            base.ValidateComputerName(strArray);
            for (int i = 0; i < strArray.Length; i++)
            {
                try
                {
                    int num2;
                    WSManConnectionInfo connectionInfo = null;
                    connectionInfo = new WSManConnectionInfo();
                    string str = this.UseSSL.IsPresent ? "https" : "http";
                    connectionInfo.ComputerName = strArray[i];
                    connectionInfo.Port         = this.Port;
                    connectionInfo.AppName      = this.ApplicationName;
                    connectionInfo.ShellUri     = this.ConfigurationName;
                    connectionInfo.Scheme       = str;
                    if (this.CertificateThumbprint != null)
                    {
                        connectionInfo.CertificateThumbprint = this.CertificateThumbprint;
                    }
                    else
                    {
                        connectionInfo.Credential = this.Credential;
                    }
                    connectionInfo.AuthenticationMechanism = this.Authentication;
                    base.UpdateConnectionInfo(connectionInfo);
                    connectionInfo.EnableNetworkAccess = (bool)this.EnableNetworkAccess;
                    string         runspaceName = this.GetRunspaceName(i, out num2);
                    RemoteRunspace item         = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, base.Host, this.SessionOption.ApplicationArguments, runspaceName, num2);
                    list.Add(item);
                }
                catch (UriFormatException exception)
                {
                    PipelineWriter  objectWriter = this.stream.ObjectWriter;
                    ErrorRecord     errorRecord  = new ErrorRecord(exception, "CreateRemoteRunspaceFailed", ErrorCategory.InvalidArgument, strArray[i]);
                    Action <Cmdlet> action       = delegate(Cmdlet cmdlet) {
                        cmdlet.WriteError(errorRecord);
                    };
                    objectWriter.Write(action);
                }
            }
            return(list);
        }
コード例 #26
0
        private List <RemoteRunspace> CreateRunspacesWhenUriParameterSpecified()
        {
            List <RemoteRunspace> list = new List <RemoteRunspace>();

            for (int i = 0; i < this.ConnectionUri.Length; i++)
            {
                try
                {
                    int num2;
                    WSManConnectionInfo connectionInfo = new WSManConnectionInfo {
                        ConnectionUri = this.ConnectionUri[i],
                        ShellUri      = this.ConfigurationName
                    };
                    if (this.CertificateThumbprint != null)
                    {
                        connectionInfo.CertificateThumbprint = this.CertificateThumbprint;
                    }
                    else
                    {
                        connectionInfo.Credential = this.Credential;
                    }
                    connectionInfo.AuthenticationMechanism = this.Authentication;
                    base.UpdateConnectionInfo(connectionInfo);
                    connectionInfo.EnableNetworkAccess = (bool)this.EnableNetworkAccess;
                    string         runspaceName = this.GetRunspaceName(i, out num2);
                    RemoteRunspace item         = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, base.Host, this.SessionOption.ApplicationArguments, runspaceName, num2);
                    list.Add(item);
                }
                catch (UriFormatException exception)
                {
                    this.WriteErrorCreateRemoteRunspaceFailed(exception, this.ConnectionUri[i]);
                }
                catch (InvalidOperationException exception2)
                {
                    this.WriteErrorCreateRemoteRunspaceFailed(exception2, this.ConnectionUri[i]);
                }
                catch (ArgumentException exception3)
                {
                    this.WriteErrorCreateRemoteRunspaceFailed(exception3, this.ConnectionUri[i]);
                }
                catch (NotSupportedException exception4)
                {
                    this.WriteErrorCreateRemoteRunspaceFailed(exception4, this.ConnectionUri[i]);
                }
            }
            return(list);
        }
コード例 #27
0
        private RemoteRunspace GetRunspaceMatchingCondition(Predicate <PSSession> condition, PSRemotingErrorId tooFew, PSRemotingErrorId tooMany, string tooFewResourceString, string tooManyResourceString, object errorArgument)
        {
            List <PSSession> list     = base.RunspaceRepository.Runspaces.FindAll(condition);
            RemoteRunspace   runspace = null;

            if (list.Count == 0)
            {
                this.WriteInvalidArgumentError(tooFew, tooFewResourceString, errorArgument);
                return(runspace);
            }
            if (list.Count > 1)
            {
                this.WriteInvalidArgumentError(tooMany, tooManyResourceString, errorArgument);
                return(runspace);
            }
            return((RemoteRunspace)list[0].Runspace);
        }
コード例 #28
0
        protected void CreateHelpersForSpecifiedRunspaces()
        {
            int length = this.Session.Length;

            RemoteRunspace[] runspaceArray = new RemoteRunspace[length];
            for (int i = 0; i < length; i++)
            {
                runspaceArray[i] = (RemoteRunspace)this.Session[i].Runspace;
            }
            Pipeline[] pipelineArray = new Pipeline[length];
            for (int j = 0; j < length; j++)
            {
                pipelineArray[j] = this.CreatePipeline(runspaceArray[j]);
                IThrottleOperation item = new ExecutionCmdletHelperRunspace(pipelineArray[j]);
                this.Operations.Add(item);
            }
        }
コード例 #29
0
        internal void ExecuteVoidMethod(PSHost clientHost)
        {
            RemoteRunspace remoteRunspace = (RemoteRunspace)null;

            if (this.IsSetShouldExitOrPopRunspace)
            {
                remoteRunspace = this.GetRemoteRunspaceToClose(clientHost);
            }
            try
            {
                this.MyMethodBase.Invoke(this.SelectTargetObject(clientHost), this._parameters);
            }
            finally
            {
                remoteRunspace?.Close();
            }
        }
コード例 #30
0
        protected void CreateHelpersForSpecifiedUris()
        {
            RemoteRunspace remoteRunspace = null;

            for (int i = 0; i < this.ConnectionUri.Length; i++)
            {
                try
                {
                    WSManConnectionInfo connectionInfo = new WSManConnectionInfo {
                        ConnectionUri = this.ConnectionUri[i],
                        ShellUri      = this.ConfigurationName
                    };
                    if (this.CertificateThumbprint != null)
                    {
                        connectionInfo.CertificateThumbprint = this.CertificateThumbprint;
                    }
                    else
                    {
                        connectionInfo.Credential = this.Credential;
                    }
                    connectionInfo.AuthenticationMechanism = this.Authentication;
                    base.UpdateConnectionInfo(connectionInfo);
                    connectionInfo.EnableNetworkAccess = (bool)this.EnableNetworkAccess;
                    remoteRunspace = (RemoteRunspace)RunspaceFactory.CreateRunspace(connectionInfo, base.Host, Utils.GetTypeTableFromExecutionContextTLS(), this.SessionOption.ApplicationArguments);
                    remoteRunspace.Events.ReceivedEvents.PSEventReceived += new PSEventReceivedEventHandler(this.OnRunspacePSEventReceived);
                }
                catch (UriFormatException exception)
                {
                    this.WriteErrorCreateRemoteRunspaceFailed(exception, this.ConnectionUri[i]);
                    continue;
                }
                catch (InvalidOperationException exception2)
                {
                    this.WriteErrorCreateRemoteRunspaceFailed(exception2, this.ConnectionUri[i]);
                    continue;
                }
                catch (ArgumentException exception3)
                {
                    this.WriteErrorCreateRemoteRunspaceFailed(exception3, this.ConnectionUri[i]);
                    continue;
                }
                Pipeline           pipeline = this.CreatePipeline(remoteRunspace);
                IThrottleOperation item     = new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline, this.invokeAndDisconnect);
                this.Operations.Add(item);
            }
        }
コード例 #31
0
ファイル: LocalConnection.cs プロジェクト: 40a/PowerShell
 /// <summary>
 /// Internal constructor
 /// </summary>
 /// <param name="remoteRunspace"></param>
 internal CloseOrDisconnectRunspaceOperationHelper(RemoteRunspace remoteRunspace)
 {
     _remoteRunspace = remoteRunspace;
     _remoteRunspace.StateChanged += new EventHandler<RunspaceStateEventArgs>(HandleRunspaceStateChanged);
 }
コード例 #32
0
ファイル: remoterunspaceinfo.cs プロジェクト: 40a/PowerShell
        /// <summary>
        /// Internal method to insert a runspace into a PSSession object.
        /// This is used only for Disconnect/Reconnect scenarios where the
        /// new runspace is a reconstructed runspace having the same Guid
        /// as the existing runspace.
        /// </summary>
        /// <param name="remoteRunspace">Runspace to insert</param>
        /// <returns>Boolean indicating if runspace was inserted.</returns>
        internal bool InsertRunspace(RemoteRunspace remoteRunspace)
        {
            if (remoteRunspace == null ||
                remoteRunspace.InstanceId != _remoteRunspace.InstanceId)
            {
                return false;
            }

            _remoteRunspace = remoteRunspace;
            return true;
        }
コード例 #33
0
ファイル: remoterunspaceinfo.cs プロジェクト: 40a/PowerShell
        /// <summary>
        /// This constructor will be used to created a remote runspace info
        /// object with a auto generated name
        /// </summary>
        /// <param name="remoteRunspace">Remote runspace object for which 
        /// the info object need to be created</param>
        internal PSSession(RemoteRunspace remoteRunspace)
        {
            _remoteRunspace = remoteRunspace;

            // Use passed in session Id, if available.
            if (remoteRunspace.PSSessionId != -1)
            {
                Id = remoteRunspace.PSSessionId;
            }
            else
            {
                Id = System.Threading.Interlocked.Increment(ref s_seed);
                remoteRunspace.PSSessionId = Id;
            }

            // Use passed in friendly name, if available.
            if (!string.IsNullOrEmpty(remoteRunspace.PSSessionName))
            {
                Name = remoteRunspace.PSSessionName;
            }
            else
            {
                Name = AutoGenerateRunspaceName(Id);
                remoteRunspace.PSSessionName = Name;
            }

            // WSMan session
            if (remoteRunspace.ConnectionInfo is WSManConnectionInfo)
            {
                ComputerType = TargetMachineType.RemoteMachine;

                string fullShellName = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo<string>(
                    remoteRunspace.ConnectionInfo,
                    "ShellUri", string.Empty);

                ConfigurationName = GetDisplayShellName(fullShellName);
                return;
            }

            // VM session
            VMConnectionInfo vmConnectionInfo = remoteRunspace.ConnectionInfo as VMConnectionInfo;
            if (vmConnectionInfo != null)
            {
                ComputerType = TargetMachineType.VirtualMachine;
                ConfigurationName = vmConnectionInfo.ConfigurationName;
                return;
            }

            // Container session
            ContainerConnectionInfo containerConnectionInfo = remoteRunspace.ConnectionInfo as ContainerConnectionInfo;
            if (containerConnectionInfo != null)
            {
                ComputerType = TargetMachineType.Container;
                ConfigurationName = containerConnectionInfo.ContainerProc.ConfigurationName;
                return;
            }

            // SSH session
            SSHConnectionInfo sshConnectionInfo = remoteRunspace.ConnectionInfo as SSHConnectionInfo;
            if (sshConnectionInfo != null)
            {
                ComputerType = TargetMachineType.RemoteMachine;
                ConfigurationName = "DefaultShell";
                return;
            }

            // We only support WSMan/VM/Container sessions now.
            Dbg.Assert(false, "Invalid Runspace");
        }
コード例 #34
0
ファイル: RunspaceRef.cs プロジェクト: dfinke/powershell
        /// <summary>
        /// Override inside a safe lock
        /// </summary>
        /// <param name="remoteRunspace">runspace to override</param>
        /// <param name="syncObject">object to use in synchronization</param>
        /// <param name="isRunspacePushed">set is runspace pushed</param>
        internal void Override(RemoteRunspace remoteRunspace, object syncObject, out bool isRunspacePushed)
        {
            lock (_localSyncObject)
            {
                _stopInvoke = false;
            }

            try
            {
                if (syncObject != null)
                {
                    lock (syncObject)
                    {
                        _runspaceRef.Override(remoteRunspace);
                        isRunspacePushed = true;
                    }
                }
                else
                {
                    _runspaceRef.Override(remoteRunspace);
                    isRunspacePushed = true;
                }

                if ((remoteRunspace.GetCurrentlyRunningPipeline() != null))
                {
                    // Don't execute command if pushed runspace is already running one.
                    return;
                }

                using (PowerShell powerShell = PowerShell.Create())
                {
                    powerShell.AddCommand("Get-Command");
                    powerShell.AddParameter("Name", new string[] { "Out-Default", "Exit-PSSession" });
                    powerShell.Runspace = _runspaceRef.Value;

                    bool isReleaseCandidateBackcompatibilityMode =
                        _runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersionWin7RC;
                    powerShell.IsGetCommandMetadataSpecialPipeline = !isReleaseCandidateBackcompatibilityMode;
                    int expectedNumberOfResults = isReleaseCandidateBackcompatibilityMode ? 2 : 3;

                    powerShell.RemotePowerShell.HostCallReceived += new EventHandler<RemoteDataEventArgs<RemoteHostCall>>(HandleHostCall);

                    IAsyncResult asyncResult = powerShell.BeginInvoke();
                    PSDataCollection<PSObject> results = new PSDataCollection<PSObject>();

                    while (!_stopInvoke)
                    {
                        asyncResult.AsyncWaitHandle.WaitOne(1000);

                        if (asyncResult.IsCompleted)
                        {
                            results = powerShell.EndInvoke(asyncResult);
                            break;
                        }
                    }

                    if (powerShell.Streams.Error.Count > 0 || results.Count < expectedNumberOfResults)
                    {
                        throw RemoteHostExceptions.NewRemoteRunspaceDoesNotSupportPushRunspaceException();
                    }
                }
            }
            catch (Exception)
            {
                _runspaceRef.Revert();
                isRunspacePushed = false;
                throw;
            }
        }
コード例 #35
0
ファイル: RunspaceRef.cs プロジェクト: dfinke/powershell
 /// <summary>
 /// Override.
 /// </summary>
 internal void Override(RemoteRunspace remoteRunspace)
 {
     bool isRunspacePushed = false;
     Override(remoteRunspace, null, out isRunspacePushed);
 }
コード例 #36
0
ファイル: ServerRemoteHost.cs プロジェクト: 40a/PowerShell
        /// <summary>
        /// Push runspace to use for remote command execution
        /// </summary>
        /// <param name="runspace">RemoteRunspace</param>
        public override void PushRunspace(Runspace runspace)
        {
            // Double session hop is currently allowed only for WSMan (non-OutOfProc) sessions, where 
            // the second session is either through a named pipe or hyperV socket connection.
            if (!AllowPushRunspace &&
                ((_transportManager is OutOfProcessServerSessionTransportManager) ||
                 !(runspace.ConnectionInfo is NamedPipeConnectionInfo ||
                   runspace.ConnectionInfo is VMConnectionInfo ||
                   runspace.ConnectionInfo is ContainerConnectionInfo))
               )
            {
                throw new PSNotSupportedException();
            }

            if (_debugger == null)
            {
                throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostNoDebuggerToPush);
            }

            if (_pushedRunspace != null)
            {
                throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostAlreadyPushed);
            }

            RemoteRunspace remoteRunspace = runspace as RemoteRunspace;
            if (remoteRunspace == null)
            {
                throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostNotRemoteRunspace);
            }

            // PSEdit support.  Existence of RemoteSessionOpenFileEvent event indicates host supports PSEdit
            _hostSupportsPSEdit = false;
            PSEventManager localEventManager = (Runspace != null) ? Runspace.Events : null;
            _hostSupportsPSEdit = (localEventManager != null) ? localEventManager.GetEventSubscribers(HostUtilities.RemoteSessionOpenFileEvent).GetEnumerator().MoveNext() : false;
            if (_hostSupportsPSEdit)
            {
                AddPSEditForRunspace(remoteRunspace);
            }

            _debugger.PushDebugger(runspace.Debugger);
            _pushedRunspace = remoteRunspace;
        }
コード例 #37
0
ファイル: ServerRemoteHost.cs プロジェクト: 40a/PowerShell
        /// <summary>
        /// Pop runspace
        /// </summary>
        public override void PopRunspace()
        {
            if (_pushedRunspace != null)
            {
                if (_debugger != null)
                {
                    _debugger.PopDebugger();
                }

                if (_hostSupportsPSEdit)
                {
                    RemovePSEditFromRunspace(_pushedRunspace);
                }

                if (_pushedRunspace.ShouldCloseOnPop)
                {
                    _pushedRunspace.Close();
                }
                _pushedRunspace = null;
            }
        }
コード例 #38
0
ファイル: ServerRemoteHost.cs プロジェクト: 40a/PowerShell
        private void AddPSEditForRunspace(RemoteRunspace remoteRunspace)
        {
            if (remoteRunspace.Events == null) { return; }

            // Add event handler.
            remoteRunspace.Events.ReceivedEvents.PSEventReceived += HandleRemoteSessionForwardedEvent;

            // Add script function.
            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.Runspace = remoteRunspace;
                powershell.AddScript(HostUtilities.CreatePSEditFunction).AddParameter("PSEditFunction", HostUtilities.PSEditFunction);
                try
                {
                    powershell.Invoke();
                }
                catch (RemoteException) { }
            }
        }
コード例 #39
0
ファイル: ServerRemoteHost.cs プロジェクト: 40a/PowerShell
        private void RemovePSEditFromRunspace(RemoteRunspace remoteRunspace)
        {
            if (remoteRunspace.Events == null) { return; }

            // It is possible for the popped runspace to be in a bad state after an error.
            if ((remoteRunspace.RunspaceStateInfo.State != RunspaceState.Opened) || (remoteRunspace.RunspaceAvailability != RunspaceAvailability.Available))
            {
                return;
            }

            // Remove event handler.
            remoteRunspace.Events.ReceivedEvents.PSEventReceived -= HandleRemoteSessionForwardedEvent;

            // Remove script function.
            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.Runspace = remoteRunspace;
                powershell.AddScript(HostUtilities.RemovePSEditFunction);
                try
                {
                    powershell.Invoke();
                }
                catch (RemoteException) { }
            }
        }