Beispiel #1
0
        internal static bool HasRepeatingRunspaces(PSSession[] runspaceInfos)
        {
            if (runspaceInfos == null)
            {
                throw PSTraceSource.NewArgumentNullException("runspaceInfos");
            }

            if (runspaceInfos.GetLength(0) == 0)
            {
                throw PSTraceSource.NewArgumentException("runspaceInfos");
            }

            for (int i = 0; i < runspaceInfos.GetLength(0); i++)
            {
                for (int k = 0; k < runspaceInfos.GetLength(0); k++)
                {
                    if (i != k)
                    {
                        if (runspaceInfos[i].Runspace.InstanceId == runspaceInfos[k].Runspace.InstanceId)
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }
 private PSSession ConnectSession(PSSession session, out Exception ex)
 {
     ex = null;
     if ((session == null) || ((session.Runspace.RunspaceStateInfo.State != RunspaceState.Opened) && (session.Runspace.RunspaceStateInfo.State != RunspaceState.Disconnected)))
     {
         return null;
     }
     if (session.Runspace.RunspaceStateInfo.State != RunspaceState.Opened)
     {
         try
         {
             session.Runspace.Connect();
         }
         catch (PSInvalidOperationException exception)
         {
             ex = exception;
         }
         catch (InvalidRunspaceStateException exception2)
         {
             ex = exception2;
         }
         catch (RuntimeException exception3)
         {
             ex = exception3;
         }
         if (ex != null)
         {
             return null;
         }
     }
     return session;
 }
Beispiel #3
0
 private void GetAvailableViaPsrpSession(string[] moduleNames, System.Management.Automation.Runspaces.PSSession session)
 {
     foreach (PSModuleInfo info in this.GetAvailableViaPsrpSessionCore(moduleNames, session.Runspace))
     {
         RemoteDiscoveryHelper.AssociatePSModuleInfoWithSession(info, session);
         base.WriteObject(info);
     }
 }
Beispiel #4
0
 internal static bool ExceedMaximumAllowableRunspaces(PSSession[] runspaceInfos)
 {
     if (runspaceInfos == null)
     {
         throw PSTraceSource.NewArgumentNullException("runspaceInfos");
     }
     if (runspaceInfos.GetLength(0) == 0)
     {
         throw PSTraceSource.NewArgumentException("runspaceInfos");
     }
     return false;
 }
Beispiel #5
0
 internal PSRemotingJob(PSSession[] remoteRunspaceInfos, List<IThrottleOperation> runspaceHelpers, string remoteCommand, int throttleLimit, string name) : base(remoteCommand, name)
 {
     this.moreData = true;
     this.hideComputerName = true;
     this.throttleManager = new ThrottleManager();
     this._syncObject = new object();
     for (int i = 0; i < remoteRunspaceInfos.Length; i++)
     {
         ExecutionCmdletHelperRunspace helper = (ExecutionCmdletHelperRunspace) runspaceHelpers[i];
         PSRemotingChildJob item = new PSRemotingChildJob(remoteCommand, helper, this.throttleManager);
         item.StateChanged += new EventHandler<JobStateEventArgs>(this.HandleChildJobStateChanged);
         item.JobUnblocked += new EventHandler(this.HandleJobUnblocked);
         base.ChildJobs.Add(item);
     }
     this.CommonInit(throttleLimit, runspaceHelpers);
 }
        /// <summary>
        /// Creates a PSSession object from the provided remote runspace object.
        /// If psCmdlet argument is non-null, then the new PSSession object is added to the
        /// session runspace repository (Get-PSSession).
        /// </summary>
        /// <param name="runspace">Runspace for the new PSSession.</param>
        /// <param name="transportName">Optional transport name.</param>
        /// <param name="psCmdlet">Optional cmdlet associated with the PSSession creation.</param>
        public static PSSession Create(
            Runspace runspace,
            string transportName,
            PSCmdlet psCmdlet)
        {
            if (!(runspace is RemoteRunspace remoteRunspace))
            {
                throw new PSArgumentException(RemotingErrorIdStrings.InvalidPSSessionArgument);
            }

            var psSession = new PSSession(remoteRunspace)
            {
                _transportName = transportName
            };

            if (psCmdlet != null)
            {
                psCmdlet.RunspaceRepository.Add(psSession);
            }

            return(psSession);
        }
        public PSModuleInfo ImportPSSession(PSSession session, Action<PSDataStreams> psDataStreamAction)
        {
            if (session == null)
            {
                throw new ArgumentOutOfRangeException("session");
            }

            var command = new PSCommand();
            command.AddCommand(Constants.SessionScripts.ImportPSSession);
            command.AddParameter(Constants.ParameterNameStrings.Session, session);
            Collection<PSModuleInfo> modules;
            try
            {
                modules = this.runspace.ExecuteCommand<PSModuleInfo>(command, psDataStreamAction);
                if (modules.Count > 0) return modules[0];
            }
            catch (Exception)
            {

                return null;
            }
            return null;
        }
 private void WriteRemoteObject(PSObject psObject, PSSession session)
 {
     if (psObject != null)
     {
         if (psObject.Properties[RemotingConstants.ComputerNameNoteProperty] == null)
         {
             psObject.Properties.Add(new PSNoteProperty(RemotingConstants.ComputerNameNoteProperty, session.ComputerName));
         }
         if (psObject.Properties[RemotingConstants.RunspaceIdNoteProperty] == null)
         {
             psObject.Properties.Add(new PSNoteProperty(RemotingConstants.RunspaceIdNoteProperty, session.InstanceId));
         }
         if (psObject.Properties[RemotingConstants.ShowComputerNameNoteProperty] == null)
         {
             psObject.Properties.Add(new PSNoteProperty(RemotingConstants.ShowComputerNameNoteProperty, true));
         }
         base.WriteObject(psObject);
     }
 }
 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;
 }
Beispiel #10
0
        private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs stateEventArgs)
        {
            ErrorRecord errorRecord;
            PSRemotingTransportException exception2;
            string str;
            if (sender == null)
            {
                throw PSTraceSource.NewArgumentNullException("sender");
            }
            if (stateEventArgs == null)
            {
                throw PSTraceSource.NewArgumentNullException("stateEventArgs");
            }
            RunspaceStateEventArgs baseEvent = stateEventArgs.BaseEvent as RunspaceStateEventArgs;
            RunspaceState state = baseEvent.RunspaceStateInfo.State;
            OpenRunspaceOperation operation = sender as OpenRunspaceOperation;
            RemoteRunspace operatedRunspace = operation.OperatedRunspace;
            if (operatedRunspace != null)
            {
                operatedRunspace.URIRedirectionReported -= new EventHandler<RemoteDataEventArgs<Uri>>(this.HandleURIDirectionReported);
            }
            PipelineWriter objectWriter = this.stream.ObjectWriter;
            Exception reason = baseEvent.RunspaceStateInfo.Reason;
            switch (state)
            {
                case RunspaceState.Opened:
                {
                    PSSession remoteRunspaceInfo = new PSSession(operatedRunspace);
                    base.RunspaceRepository.Add(remoteRunspaceInfo);
                    Action<Cmdlet> action = cmdlet => cmdlet.WriteObject(remoteRunspaceInfo);
                    if (objectWriter.IsOpen)
                    {
                        objectWriter.Write(action);
                    }
                    return;
                }
                case RunspaceState.Closed:
                {
                    Uri uri = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo<Uri>(operatedRunspace.ConnectionInfo, "ConnectionUri", null);
                    string message = base.GetMessage(RemotingErrorIdStrings.RemoteRunspaceClosed, new object[] { (uri != null) ? uri.AbsoluteUri : string.Empty });
                    Action<Cmdlet> action3 = cmdlet => cmdlet.WriteVerbose(message);
                    if (objectWriter.IsOpen)
                    {
                        objectWriter.Write(action3);
                    }
                    if (reason != null)
                    {
                        ErrorRecord errorRecord2 = new ErrorRecord(reason, "PSSessionStateClosed", ErrorCategory.OpenError, operatedRunspace);
                        Action<Cmdlet> action4 = cmdlet => cmdlet.WriteError(errorRecord2);
                        if (objectWriter.IsOpen)
                        {
                            objectWriter.Write(action4);
                        }
                    }
                    return;
                }
                case RunspaceState.Closing:
                    return;

                case RunspaceState.Broken:
                    exception2 = reason as PSRemotingTransportException;
                    str = null;
                    if (exception2 != null)
                    {
                        OpenRunspaceOperation operation2 = sender as OpenRunspaceOperation;
                        if (operation2 != null)
                        {
                            string computerName = operation2.OperatedRunspace.ConnectionInfo.ComputerName;
                            if (exception2.ErrorCode != -2144108135)
                            {
                                str = "[" + computerName + "] ";
                                if (!string.IsNullOrEmpty(exception2.Message))
                                {
                                    str = str + exception2.Message;
                                }
                                else if (!string.IsNullOrEmpty(exception2.TransportMessage))
                                {
                                    str = str + exception2.TransportMessage;
                                }
                                break;
                            }
                            string str3 = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.URIRedirectionReported, new object[] { exception2.Message, "MaximumConnectionRedirectionCount", "PSSessionOption", "AllowRedirection" });
                            str = "[" + computerName + "] " + str3;
                        }
                    }
                    break;

                default:
                    return;
            }
            PSRemotingDataStructureException exception3 = reason as PSRemotingDataStructureException;
            if (exception3 != null)
            {
                OpenRunspaceOperation operation3 = sender as OpenRunspaceOperation;
                if (operation3 != null)
                {
                    string str4 = operation3.OperatedRunspace.ConnectionInfo.ComputerName;
                    str = "[" + str4 + "] " + exception3.Message;
                }
            }
            if (reason == null)
            {
                reason = new RuntimeException(base.GetMessage(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, new object[] { state }));
            }
            string fQEIDFromTransportError = WSManTransportManagerUtils.GetFQEIDFromTransportError((exception2 != null) ? exception2.ErrorCode : 0, this._defaultFQEID);
            errorRecord = new ErrorRecord(reason, operatedRunspace, fQEIDFromTransportError, ErrorCategory.OpenError, null, null, null, null, null, str, null);
            Action<Cmdlet> action2 = cmdlet => cmdlet.WriteError(errorRecord);
            if (objectWriter.IsOpen)
            {
                objectWriter.Write(action2);
            }
            this.toDispose.Add(operatedRunspace);
        }
Beispiel #11
0
        private IList<PSModuleInfo> ImportModule_RemotelyViaPsrpSession(
            ImportModuleOptions importModuleOptions,
            string moduleName,
            ModuleSpecification fullyQualifiedName,
            PSSession psSession)
        {
            //
            // import the module in the remote session first
            //
            List<PSObject> remotelyImportedModules;
            using (var powerShell = System.Management.Automation.PowerShell.Create())
            {
                powerShell.Runspace = psSession.Runspace;
                powerShell.AddCommand("Import-Module");
                powerShell.AddParameter("DisableNameChecking", this.DisableNameChecking);
                powerShell.AddParameter("PassThru", true);

                if (fullyQualifiedName != null)
                {
                    powerShell.AddParameter("FullyQualifiedName", fullyQualifiedName);
                }
                else
                {
                    powerShell.AddParameter("Name", moduleName);

                    if (this.MinimumVersion != null)
                    {
                        powerShell.AddParameter("Version", this.MinimumVersion);
                    }
                    if (this.RequiredVersion != null)
                    {
                        powerShell.AddParameter("RequiredVersion", this.RequiredVersion);
                    }
                    if (this.MaximumVersion != null)
                    {
                        powerShell.AddParameter("MaximumVersion", this.MaximumVersion);
                    }
                }
                if (this.ArgumentList != null)
                {
                    powerShell.AddParameter("ArgumentList", this.ArgumentList);
                }
                if (this.BaseForce)
                {
                    powerShell.AddParameter("Force", true);
                }

                string errorMessageTemplate = string.Format(
                    CultureInfo.InvariantCulture,
                    Modules.RemoteDiscoveryRemotePsrpCommandFailed,
                    string.Format(CultureInfo.InvariantCulture, "Import-Module -Name '{0}'", moduleName));
                remotelyImportedModules = RemoteDiscoveryHelper.InvokePowerShell(
                    powerShell,
                    this.CancellationToken,
                    this,
                    errorMessageTemplate).ToList();
            }

            List<PSModuleInfo> result = new List<PSModuleInfo>();
            foreach (PSObject remotelyImportedModule in remotelyImportedModules)
            {
                PSPropertyInfo nameProperty = remotelyImportedModule.Properties["Name"];
                if (nameProperty != null)
                {
                    string remoteModuleName = (string)LanguagePrimitives.ConvertTo(
                        nameProperty.Value,
                        typeof(string),
                        CultureInfo.InvariantCulture);

                    PSPropertyInfo helpInfoProperty = remotelyImportedModule.Properties["HelpInfoUri"];
                    string remoteHelpInfoUri = null;
                    if (helpInfoProperty != null)
                    {
                        remoteHelpInfoUri = (string)LanguagePrimitives.ConvertTo(
                            helpInfoProperty.Value,
                            typeof(string),
                            CultureInfo.InvariantCulture);
                    }

                    PSPropertyInfo guidProperty = remotelyImportedModule.Properties["Guid"];
                    Guid remoteModuleGuid = Guid.Empty;
                    if (guidProperty != null)
                    {
                        LanguagePrimitives.TryConvertTo(guidProperty.Value, out remoteModuleGuid);
                    }

                    PSPropertyInfo versionProperty = remotelyImportedModule.Properties["Version"];
                    Version remoteModuleVersion = null;
                    if (versionProperty != null)
                    {
                        Version tmp;
                        if (LanguagePrimitives.TryConvertTo<Version>(versionProperty.Value, CultureInfo.InvariantCulture, out tmp))
                        {
                            remoteModuleVersion = tmp;
                        }
                    }

                    PSModuleInfo moduleInfo = ImportModule_RemotelyViaPsrpSession_SinglePreimportedModule(
                        importModuleOptions,
                        remoteModuleName,
                        remoteModuleVersion,
                        psSession);

                    // Set the HelpInfoUri and Guid as necessary, so that Save-Help can work with this module object
                    // to retrieve help files from the remote site.
                    if (moduleInfo != null)
                    {
                        // set the HelpInfoUri if it's needed
                        if (string.IsNullOrEmpty(moduleInfo.HelpInfoUri) && !string.IsNullOrEmpty(remoteHelpInfoUri))
                        {
                            moduleInfo.SetHelpInfoUri(remoteHelpInfoUri);
                        }

                        // set the Guid if it's needed
                        if (remoteModuleGuid != Guid.Empty)
                        {
                            moduleInfo.SetGuid(remoteModuleGuid);
                        }

                        result.Add(moduleInfo);
                    }
                }
            }

            return result;
        }
Beispiel #12
0
        private void GetAvailableViaPsrpSession(string[] names, IDictionary<string, ModuleSpecification> moduleSpecTable, PSSession session)
        {
            var remoteModules = GetAvailableViaPsrpSessionCore(names, session.Runspace);

            foreach (var remoteModule in remoteModules.Where(remoteModule => ModuleMatch(remoteModule, moduleSpecTable, PSEdition))
                )
            {
                RemoteDiscoveryHelper.AssociatePSModuleInfoWithSession(remoteModule, session);
                this.WriteObject(remoteModule);
            }
        }
Beispiel #13
0
        /// <summary>
        /// Helper method to append computer name and session GUID
        /// note properties to the PSObject before it is written.
        /// </summary>
        /// <param name="psObject">PSObject</param>
        /// <param name="session">PSSession</param>
        private void WriteRemoteObject(
            PSObject psObject,
            PSSession session)
        {
            if (psObject == null)
            {
                return;
            }

            // Add note properties for this session if they don't already exist.
            if (psObject.Properties[RemotingConstants.ComputerNameNoteProperty] == null)
            {
                psObject.Properties.Add(new PSNoteProperty(RemotingConstants.ComputerNameNoteProperty, session.ComputerName));
            }
            if (psObject.Properties[RemotingConstants.RunspaceIdNoteProperty] == null)
            {
                psObject.Properties.Add(new PSNoteProperty(RemotingConstants.RunspaceIdNoteProperty, session.InstanceId));
            }
            if (psObject.Properties[RemotingConstants.ShowComputerNameNoteProperty] == null)
            {
                psObject.Properties.Add(new PSNoteProperty(RemotingConstants.ShowComputerNameNoteProperty, true));
            }

            WriteObject(psObject);
        }
 internal DisconnectRunspaceOperation(PSSession session, ObjectStream stream)
 {
     this.remoteSession = session;
     this.writeStream = stream;
     this.remoteSession.Runspace.StateChanged += new EventHandler<RunspaceStateEventArgs>(this.StateCallBackHandler);
 }
 private bool ValidateIdleTimeout(PSSession session)
 {
     int idleTimeout = session.Runspace.ConnectionInfo.IdleTimeout;
     int maxIdleTimeout = session.Runspace.ConnectionInfo.MaxIdleTimeout;
     int num3 = 0xea60;
     if ((idleTimeout == -1) || ((idleTimeout <= maxIdleTimeout) && (idleTimeout >= num3)))
     {
         return true;
     }
     ErrorRecord errorRecord = new ErrorRecord(new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.CannotDisconnectSessionWithInvalidIdleTimeout, new object[] { session.Name, idleTimeout / 0x3e8, maxIdleTimeout / 0x3e8, num3 / 0x3e8 })), "CannotDisconnectSessionWithInvalidIdleTimeout", ErrorCategory.InvalidArgument, session);
     base.WriteError(errorRecord);
     return false;
 }
Beispiel #16
0
            private void WriteConnectFailed(
                Exception e,
                PSSession session)
            {
                if (_writeStream.ObjectWriter.IsOpen)
                {
                    string FQEID = "PSSessionConnectFailed";
                    Exception reason;
                    if (e != null && !string.IsNullOrEmpty(e.Message))
                    {
                        // Update fully qualified error Id if we have a transport error.
                        PSRemotingTransportException transportException = e as PSRemotingTransportException;
                        if (transportException != null)
                        {
                            FQEID = WSManTransportManagerUtils.GetFQEIDFromTransportError(transportException.ErrorCode, FQEID);
                        }

                        reason = new RuntimeException(
                            StringUtil.Format(RemotingErrorIdStrings.RunspaceConnectFailedWithMessage, session.Name, e.Message),
                            e);
                    }
                    else
                    {
                        reason = new RuntimeException(
                            StringUtil.Format(RemotingErrorIdStrings.RunspaceConnectFailed, session.Name,
                                session.Runspace.RunspaceStateInfo.State.ToString()), null);
                    }
                    ErrorRecord errorRecord = new ErrorRecord(reason, FQEID, ErrorCategory.InvalidOperation, null);
                    Action<Cmdlet> errorWriter = delegate (Cmdlet cmdlet)
                    {
                        cmdlet.WriteError(errorRecord);
                    };
                    _writeStream.ObjectWriter.Write(errorWriter);
                }
            }
Beispiel #17
0
 internal DisconnectRunspaceOperation(PSSession session, ObjectStream stream)
 {
     _remoteSession = session;
     _writeStream = stream;
     _remoteSession.Runspace.StateChanged += StateCallBackHandler;
 }
Beispiel #18
0
        /// <summary>
        /// Connects session, collects command output data in a job object.
        /// If a PSRemotingJob object is passed in then that job will be
        /// (re)connected.  Otherwise a new job object will be created that
        /// will be connected to the session's running command.
        /// </summary>
        /// <param name="session">PSSession object.</param>
        /// <param name="job">Job object to connect to.</param>
        private void ConnectSessionToJob(PSSession session, PSRemotingJob job = null)
        {
            // Otherwise create a new job object in the disconnected state for this
            // session and then connect it.
            bool newJobCreated = false;
            if (job == null)
            {
                // The PSRemoting job object uses helper objects to track remote command execution.
                List<IThrottleOperation> helpers = new List<IThrottleOperation>();

                // Create the remote pipeline object that will represent the running command
                // on the server machine.  This object will be in the disconnected state.
                Pipeline remotePipeline = session.Runspace.CreateDisconnectedPipeline();

                // Create a disconnected runspace helper for this remote command.
                helpers.Add(new DisconnectedJobOperation(remotePipeline));

                // Create the job object in a disconnected state.  Note that the job name
                // will be autogenerated.
                job = new PSRemotingJob(helpers, 0, JobName, false);
                job.PSJobTypeName = InvokeCommandCommand.RemoteJobType;
                job.HideComputerName = false;
                newJobCreated = true;
            }

            if (job.JobStateInfo.State == JobState.Disconnected)
            {
                // Connect the job to the remote command running on the server.
                job.ConnectJob(session.Runspace.InstanceId);

                // Add the created job to the store if it was connected successfully.
                if (newJobCreated)
                {
                    JobRepository.Add(job);
                }
            }

            if (CheckForDebugMode(session, true)) { return; }

            // Write the job object to output.
            WriteObject(job);
        }
Beispiel #19
0
        private IList<PSModuleInfo> ImportModule_RemotelyViaPsrpSession(
            ImportModuleOptions importModuleOptions,
            IEnumerable<string> moduleNames,
            IEnumerable<ModuleSpecification> fullyQualifiedNames,
            PSSession psSession)
        {
            var remotelyImportedModules = new List<PSModuleInfo>();
            if (moduleNames != null)
            {
                foreach (string moduleName in moduleNames)
                {
                    var tmp = ImportModule_RemotelyViaPsrpSession(importModuleOptions, moduleName, null, psSession);
                    remotelyImportedModules.AddRange(tmp);
                }
            }

            if (fullyQualifiedNames != null)
            {
                foreach (var fullyQualifiedName in fullyQualifiedNames)
                {
                    var tmp = ImportModule_RemotelyViaPsrpSession(importModuleOptions, null, fullyQualifiedName, psSession);
                    remotelyImportedModules.AddRange(tmp);
                }
            }

            return remotelyImportedModules;
        }
Beispiel #20
0
        /// <summary>
        /// Helper method to connect the runspace.  If the session/runspace can't
        /// be connected or fails to be connected then a null PSSessionobject is 
        /// returned.
        /// </summary>
        /// <param name="session">Session to connect.</param>
        /// <param name="ex">Optional exception object.</param>
        /// <returns>Connected session or null.</returns>
        private PSSession ConnectSession(PSSession session, out Exception ex)
        {
            ex = null;

            if (session == null ||
                (session.Runspace.RunspaceStateInfo.State != RunspaceState.Opened &&
                 session.Runspace.RunspaceStateInfo.State != RunspaceState.Disconnected))
            {
                return null;
            }
            else if (session.Runspace.RunspaceStateInfo.State == RunspaceState.Opened)
            {
                return session;
            }

            try
            {
                session.Runspace.Connect();
            }
            catch (PSInvalidOperationException e)
            {
                ex = e;
            }
            catch (InvalidRunspaceStateException e)
            {
                ex = e;
            }
            catch (RuntimeException e)
            {
                ex = e;
            }

            return (ex == null) ? session : null;
        }
Beispiel #21
0
        private PSModuleInfo ImportModule_RemotelyViaPsrpSession_SinglePreimportedModule(
            ImportModuleOptions importModuleOptions,
            string remoteModuleName,
            Version remoteModuleVersion,
            PSSession psSession)
        {
            string temporaryModulePath = RemoteDiscoveryHelper.GetModulePath(
                remoteModuleName,
                remoteModuleVersion,
                psSession.ComputerName,
                this.Context.CurrentRunspace);
            string wildcardEscapedPath = WildcardPattern.Escape(temporaryModulePath);
            try
            {
                //
                // avoid importing a module twice
                //
                string localPsm1File = Path.Combine(temporaryModulePath, Path.GetFileName(temporaryModulePath) + ".psm1");
                PSModuleInfo alreadyImportedModule = this.IsModuleImportUnnecessaryBecauseModuleIsAlreadyLoaded(
                    localPsm1File, this.BasePrefix, importModuleOptions);
                if (alreadyImportedModule != null)
                {
                    return alreadyImportedModule;
                }

                //
                // create proxy module in a temporary folder
                //
                using (var powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
                {
                    powerShell.AddCommand("Export-PSSession");
                    powerShell.AddParameter("OutputModule", wildcardEscapedPath);
                    powerShell.AddParameter("AllowClobber", true);
                    powerShell.AddParameter("Module", remoteModuleName); // remoteModulePath is currently unsupported by Get-Command and implicit remoting
                    powerShell.AddParameter("Force", true);
                    powerShell.AddParameter("FormatTypeName", "*");
                    powerShell.AddParameter("Session", psSession);

                    string errorMessageTemplate = string.Format(
                        CultureInfo.InvariantCulture,
                        Modules.RemoteDiscoveryFailedToGenerateProxyForRemoteModule,
                        remoteModuleName);
                    int numberOfLocallyCreatedFiles = RemoteDiscoveryHelper.InvokePowerShell(powerShell, this.CancellationToken, this, errorMessageTemplate).Count();
                    if (numberOfLocallyCreatedFiles == 0)
                    {
                        return null;
                    }
                }

                //
                // rename the psd1 file
                //
                string localPsd1File = Path.Combine(temporaryModulePath, remoteModuleName + ".psd1");
                if (File.Exists(localPsd1File))
                {
                    File.Delete(localPsd1File);
                }
                File.Move(
                    sourceFileName: Path.Combine(temporaryModulePath, Path.GetFileName(temporaryModulePath) + ".psd1"),
                    destFileName: localPsd1File);
                string wildcardEscapedPsd1Path = WildcardPattern.Escape(localPsd1File);

                //
                // import the proxy module just as any other local module
                //
                object[] oldArgumentList = this.ArgumentList;
                try
                {
                    this.ArgumentList = new object[] { psSession };
                    ImportModule_LocallyViaName(importModuleOptions, wildcardEscapedPsd1Path);
                }
                finally
                {
                    this.ArgumentList = oldArgumentList;
                }

                //
                // make sure the temporary folder gets removed when the module is removed
                //
                PSModuleInfo moduleInfo;
                string psm1Path = Path.Combine(temporaryModulePath, Path.GetFileName(temporaryModulePath) + ".psm1");
                if (!this.Context.Modules.ModuleTable.TryGetValue(psm1Path, out moduleInfo))
                {
                    if (Directory.Exists(temporaryModulePath))
                    {
                        Directory.Delete(temporaryModulePath, recursive: true);
                    }
                    return null;
                }

                const string onRemoveScriptBody = @"
                    Microsoft.PowerShell.Management\Remove-Item `
                        -LiteralPath $temporaryModulePath `
                        -Force `
                        -Recurse `
                        -ErrorAction SilentlyContinue

                    if ($previousOnRemoveScript -ne $null)
                    {
                        & $previousOnRemoveScript $args
                    }
                    ";
                ScriptBlock onRemoveScriptBlock = this.Context.Engine.ParseScriptBlock(onRemoveScriptBody, false);
                onRemoveScriptBlock = onRemoveScriptBlock.GetNewClosure(); // create a separate scope for variables set below
                onRemoveScriptBlock.Module.SessionState.PSVariable.Set("temporaryModulePath", temporaryModulePath);
                onRemoveScriptBlock.Module.SessionState.PSVariable.Set("previousOnRemoveScript", moduleInfo.OnRemove);
                moduleInfo.OnRemove = onRemoveScriptBlock;

                return moduleInfo;
            }
            catch
            {
                if (Directory.Exists(temporaryModulePath))
                {
                    Directory.Delete(temporaryModulePath, recursive: true);
                }
                throw;
            }
        }
Beispiel #22
0
        /// <summary>
        /// Helper method to attempt to retrieve a disconnected runspace object
        /// from the server, based on the provided session object.
        /// </summary>
        /// <param name="session">PSSession</param>
        /// <returns>PSSession</returns>
        private PSSession TryGetSessionFromServer(PSSession session)
        {
            RemoteRunspace remoteRunspace = session.Runspace as RemoteRunspace;
            if (remoteRunspace == null)
            {
                return null;
            }

            remoteRunspace = null;
            Runspace[] runspaces = Runspace.GetRunspaces(session.Runspace.ConnectionInfo, this.Host, QueryRunspaces.BuiltInTypesTable);
            foreach (Runspace runspace in runspaces)
            {
                if (runspace.InstanceId == session.Runspace.InstanceId)
                {
                    remoteRunspace = runspace as RemoteRunspace;
                    break;
                }
            }

            if (remoteRunspace != null)
            {
                // Try inserting connected runspace into existing PSSession.
                session = session.InsertRunspace(remoteRunspace) ? session : new PSSession(remoteRunspace);
                return session;
            }

            return null;
        }
Beispiel #23
0
        /// <summary>
        /// Handles state changes for Runspace
        /// </summary>
        /// <param name="sender">Sender of this event</param>
        /// <param name="stateEventArgs">Event information object which describes
        /// the event which triggered this method</param>
        private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs stateEventArgs)
        {
            if (sender == null)
            {
                throw PSTraceSource.NewArgumentNullException("sender");
            }

            if (stateEventArgs == null)
            {
                throw PSTraceSource.NewArgumentNullException("stateEventArgs");
            }

            RunspaceStateEventArgs runspaceStateEventArgs =
                        stateEventArgs.BaseEvent as RunspaceStateEventArgs;
            RunspaceStateInfo stateInfo = runspaceStateEventArgs.RunspaceStateInfo;
            RunspaceState state = stateInfo.State;
            OpenRunspaceOperation operation = sender as OpenRunspaceOperation;
            RemoteRunspace remoteRunspace = operation.OperatedRunspace;

            // since we got state changed event..we dont need to listen on
            // URI redirections anymore
            if (null != remoteRunspace)
            {
                remoteRunspace.URIRedirectionReported -= HandleURIDirectionReported;
            }

            PipelineWriter writer = _stream.ObjectWriter;
            Exception reason = runspaceStateEventArgs.RunspaceStateInfo.Reason;

            switch (state)
            {
                case RunspaceState.Opened:
                    {
                        // Indicates that runspace is successfully opened
                        // Write it to PipelineWriter to be handled in 
                        // HandleRemoteRunspace
                        PSSession remoteRunspaceInfo = new PSSession(remoteRunspace);

                        this.RunspaceRepository.Add(remoteRunspaceInfo);

                        Action<Cmdlet> outputWriter = delegate (Cmdlet cmdlet)
                        {
                            cmdlet.WriteObject(remoteRunspaceInfo);
                        };
                        if (writer.IsOpen)
                        {
                            writer.Write(outputWriter);
                        }
                    }
                    break;

                case RunspaceState.Broken:
                    {
                        // Open resulted in a broken state. Extract reason
                        // and write an error record

                        // set the transport message in the error detail so that
                        // the user can directly get to see the message without
                        // having to mine through the error record details
                        PSRemotingTransportException transException =
                            reason as PSRemotingTransportException;
                        String errorDetails = null;
                        int transErrorCode = 0;
                        if (transException != null)
                        {
                            OpenRunspaceOperation senderAsOp = sender as OpenRunspaceOperation;
                            transErrorCode = transException.ErrorCode;
                            if (senderAsOp != null)
                            {
                                String host = senderAsOp.OperatedRunspace.ConnectionInfo.ComputerName;

                                if (transException.ErrorCode ==
                                    System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_REDIRECT_REQUESTED)
                                {
                                    // Handling a special case for redirection..we should talk about
                                    // AllowRedirection parameter and WSManMaxRedirectionCount preference
                                    // variables
                                    string message = PSRemotingErrorInvariants.FormatResourceString(
                                        RemotingErrorIdStrings.URIRedirectionReported,
                                        transException.Message,
                                        "MaximumConnectionRedirectionCount",
                                        Microsoft.PowerShell.Commands.PSRemotingBaseCmdlet.DEFAULT_SESSION_OPTION,
                                        "AllowRedirection");

                                    errorDetails = "[" + host + "] " + message;
                                }
                                else
                                {
                                    errorDetails = "[" + host + "] ";
                                    if (!String.IsNullOrEmpty(transException.Message))
                                    {
                                        errorDetails += transException.Message;
                                    }
                                    else if (!String.IsNullOrEmpty(transException.TransportMessage))
                                    {
                                        errorDetails += transException.TransportMessage;
                                    }
                                }
                            }
                        }

                        // add host identification information in data structure handler message
                        PSRemotingDataStructureException protoExeption = reason as PSRemotingDataStructureException;

                        if (protoExeption != null)
                        {
                            OpenRunspaceOperation senderAsOp = sender as OpenRunspaceOperation;

                            if (senderAsOp != null)
                            {
                                String host = senderAsOp.OperatedRunspace.ConnectionInfo.ComputerName;

                                errorDetails = "[" + host + "] " + protoExeption.Message;
                            }
                        }

                        if (reason == null)
                        {
                            reason = new RuntimeException(this.GetMessage(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, state));
                        }

                        string fullyQualifiedErrorId = WSManTransportManagerUtils.GetFQEIDFromTransportError(
                            transErrorCode,
                            _defaultFQEID);

                        if (WSManNativeApi.ERROR_WSMAN_NO_LOGON_SESSION_EXIST == transErrorCode)
                        {
                            errorDetails += System.Environment.NewLine + String.Format(System.Globalization.CultureInfo.CurrentCulture, RemotingErrorIdStrings.RemotingErrorNoLogonSessionExist);
                        }
                        ErrorRecord errorRecord = new ErrorRecord(reason,
                             remoteRunspace, fullyQualifiedErrorId,
                                   ErrorCategory.OpenError, null, null,
                                        null, null, null, errorDetails, null);

                        Action<Cmdlet> errorWriter = delegate (Cmdlet cmdlet)
                        {
                            //
                            // In case of PSDirectException, we should output the precise error message
                            // in inner exception instead of the generic one in outer exception.
                            //
                            if ((errorRecord.Exception != null) &&
                                (errorRecord.Exception.InnerException != null))
                            {
                                PSDirectException ex = errorRecord.Exception.InnerException as PSDirectException;
                                if (ex != null)
                                {
                                    errorRecord = new ErrorRecord(errorRecord.Exception.InnerException,
                                                                  errorRecord.FullyQualifiedErrorId,
                                                                  errorRecord.CategoryInfo.Category,
                                                                  errorRecord.TargetObject);
                                }
                            }

                            cmdlet.WriteError(errorRecord);
                        };
                        if (writer.IsOpen)
                        {
                            writer.Write(errorWriter);
                        }

                        _toDispose.Add(remoteRunspace);
                    }
                    break;

                case RunspaceState.Closed:
                    {
                        // The runspace was closed possibly because the user
                        // hit ctrl-C when runspaces were being opened or Dispose has been
                        // called when there are open runspaces
                        Uri connectionUri = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo<Uri>(remoteRunspace.ConnectionInfo,
                            "ConnectionUri", null);
                        String message =
                            GetMessage(RemotingErrorIdStrings.RemoteRunspaceClosed,
                                        (connectionUri != null) ?
                                        connectionUri.AbsoluteUri : string.Empty);

                        Action<Cmdlet> verboseWriter = delegate (Cmdlet cmdlet)
                        {
                            cmdlet.WriteVerbose(message);
                        };
                        if (writer.IsOpen)
                        {
                            writer.Write(verboseWriter);
                        }

                        // runspace may not have been opened in certain cases
                        // like when the max memory is set to 25MB, in such 
                        // cases write an error record
                        if (reason != null)
                        {
                            ErrorRecord errorRecord = new ErrorRecord(reason,
                                 "PSSessionStateClosed",
                                       ErrorCategory.OpenError, remoteRunspace);

                            Action<Cmdlet> errorWriter = delegate (Cmdlet cmdlet)
                            {
                                cmdlet.WriteError(errorRecord);
                            };
                            if (writer.IsOpen)
                            {
                                writer.Write(errorWriter);
                            }
                        }
                    }
                    break;
            }// switch
        } // HandleRunspaceStateChanged
Beispiel #24
0
        /// <summary>
        /// Helper method to search the local PS client job repository
        /// for a job associated with the provided session.
        /// </summary>
        /// <param name="session">PSSession object.</param>
        /// <returns>Associated job object from the job repository.</returns>
        private PSRemotingJob FindJobForSession(PSSession session)
        {
            PSRemotingJob job = null;
            RemoteRunspace remoteSessionRunspace = session.Runspace as RemoteRunspace;

            if (remoteSessionRunspace == null ||
                remoteSessionRunspace.RemoteCommand != null)
            {
                // The provided session is created for *reconstruction* and we
                // cannot connect a previous job even if one exists.  A new job
                // will have to be created.
                return null;
            }

            foreach (Job repJob in this.JobRepository.Jobs)
            {
                if (repJob is PSRemotingJob)
                {
                    foreach (PSRemotingChildJob childJob in repJob.ChildJobs)
                    {
                        if (childJob.Runspace.InstanceId.Equals(session.InstanceId) &&
                            (childJob.JobStateInfo.State == JobState.Disconnected))
                        {
                            job = (PSRemotingJob)repJob;
                            break;
                        }
                    }

                    if (job != null)
                    {
                        break;
                    }
                }
            }

            return job;
        }
 private void ConnectSessionToJob(PSSession session, PSRemotingJob job = null)
 {
     bool flag = false;
     if (job == null)
     {
         List<IThrottleOperation> helpers = new List<IThrottleOperation>();
         Pipeline pipeline = session.Runspace.CreateDisconnectedPipeline();
         helpers.Add(new DisconnectedJobOperation(pipeline));
         job = new PSRemotingJob(helpers, 0, this.JobName, false);
         job.PSJobTypeName = InvokeCommandCommand.RemoteJobType;
         job.HideComputerName = false;
         flag = true;
     }
     if (job.JobStateInfo.State == JobState.Disconnected)
     {
         job.ConnectJob(session.Runspace.InstanceId);
         if (flag)
         {
             base.JobRepository.Add(job);
         }
     }
     base.WriteObject(job);
 }
Beispiel #26
0
        /// <summary>
        /// Queries the remote computer for the specified session, creates a disconnected
        /// session object, connects the runspace/command and collects command data.
        /// Command output is either returned (OutTarget.Host) or collected
        /// in a job object that is returned (OutTarget.Job).
        /// </summary>
        /// <param name="name">Name of session to find.</param>
        /// <param name="instanceId">Instance Id of session to find.</param>
        private void QueryForAndConnectCommands(string name, Guid instanceId)
        {
            WSManConnectionInfo connectionInfo = GetConnectionObject();

            // Retrieve all disconnected runspaces on the remote computer.
            Runspace[] runspaces;
            try
            {
                runspaces = Runspace.GetRunspaces(connectionInfo, this.Host, QueryRunspaces.BuiltInTypesTable);
            }
            catch (System.Management.Automation.RuntimeException e)
            {
                int errorCode;
                string msg = StringUtil.Format(RemotingErrorIdStrings.QueryForRunspacesFailed, connectionInfo.ComputerName,
                    QueryRunspaces.ExtractMessage(e.InnerException, out errorCode));
                string FQEID = WSManTransportManagerUtils.GetFQEIDFromTransportError(errorCode, "ReceivePSSessionQueryForSessionFailed");
                Exception reason = new RuntimeException(msg, e.InnerException);
                ErrorRecord errorRecord = new ErrorRecord(reason, FQEID, ErrorCategory.InvalidOperation, connectionInfo);
                WriteError(errorRecord);
                return;
            }

            // Convert configuration name into shell Uri for comparison.
            string shellUri = null;
            if (!string.IsNullOrEmpty(ConfigurationName))
            {
                shellUri = (ConfigurationName.IndexOf(
                            System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix, StringComparison.OrdinalIgnoreCase) != -1) ?
                            ConfigurationName : System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix + ConfigurationName;
            }

            // Connect selected runspace/command and direct command output to host
            // or job objects.
            foreach (Runspace runspace in runspaces)
            {
                if (_stopProcessing)
                {
                    break;
                }

                // Filter returned runspaces by ConfigurationName if provided.
                if (shellUri != null)
                {
                    // Compare with returned shell Uri in connection info.
                    WSManConnectionInfo wsmanConnectionInfo = runspace.ConnectionInfo as WSManConnectionInfo;
                    if (wsmanConnectionInfo != null &&
                        !shellUri.Equals(wsmanConnectionInfo.ShellUri, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }
                }

                // Find specified session.
                bool haveMatch = false;
                if (!string.IsNullOrEmpty(name) &&
                    string.Compare(name, ((RemoteRunspace)runspace).RunspacePool.RemoteRunspacePoolInternal.Name, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // Selected by friendly name.
                    haveMatch = true;
                }
                else if (instanceId.Equals(runspace.InstanceId))
                {
                    // Selected by instance Id (note that session/runspace/runspacepool instanceIds are identical.)
                    haveMatch = true;
                }

                if (haveMatch &&
                    ShouldProcess(((RemoteRunspace)runspace).PSSessionName, VerbsCommunications.Receive))
                {
                    // Check the local repository for an existing viable session.
                    PSSession locSession = this.RunspaceRepository.GetItem(runspace.InstanceId);

                    // Connect the session here.  If it fails (connectedSession == null) revert to the 
                    // reconstruct method.
                    Exception ex;
                    PSSession connectedSession = ConnectSession(locSession, out ex);

                    if (connectedSession != null)
                    {
                        // Make sure that this connected session is included in the PSSession repository.
                        // If it already exists then replace it because we want the latest/connected session in the repository.
                        this.RunspaceRepository.AddOrReplace(connectedSession);

                        // Since we have a local runspace we will do a *reconnect* operation and will
                        // need the corresponding job object.
                        PSRemotingJob job = FindJobForSession(connectedSession);
                        if (this.OutTarget == OutTarget.Host)
                        {
                            ConnectSessionToHost(connectedSession, job);
                        }
                        else
                        {
                            // Connection to Job is default option.
                            ConnectSessionToJob(connectedSession, job);
                        }
                    }
                    else
                    {
                        // Otherwise create a new session from the queried runspace object.
                        // This will be a *reconstruct* operation.
                        // Create and connect session.
                        PSSession newSession = new PSSession(runspace as RemoteRunspace);
                        connectedSession = ConnectSession(newSession, out ex);
                        if (connectedSession != null)
                        {
                            // Try to reuse the existing local repository PSSession object.
                            if (locSession != null)
                            {
                                connectedSession = locSession.InsertRunspace(connectedSession.Runspace as RemoteRunspace) ? locSession : connectedSession;
                            }

                            // Make sure that this connected session is included in the PSSession repository.
                            // If it already exists then replace it because we want the latest/connected session in the repository.
                            this.RunspaceRepository.AddOrReplace(connectedSession);

                            if (this.OutTarget == OutTarget.Job)
                            {
                                ConnectSessionToJob(connectedSession);
                            }
                            else
                            {
                                // Connection to Host is default option.
                                ConnectSessionToHost(connectedSession);
                            }
                        }
                        else
                        {
                            String message = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeConnected, newSession.Name);
                            WriteError(new ErrorRecord(new ArgumentException(message, ex), "ReceivePSSessionCannotConnectSession",
                                       ErrorCategory.InvalidOperation, newSession));
                        }
                    }

                    break;
                }
            }
        }
 private void QueryForAndConnectCommands(string name, Guid instanceId)
 {
     Runspace[] runspaceArray;
     WSManConnectionInfo connectionObject = this.GetConnectionObject();
     try
     {
         runspaceArray = Runspace.GetRunspaces(connectionObject, base.Host, QueryRunspaces.BuiltInTypesTable);
     }
     catch (RuntimeException exception)
     {
         int num;
         string message = StringUtil.Format(RemotingErrorIdStrings.QueryForRunspacesFailed, connectionObject.ComputerName, QueryRunspaces.ExtractMessage(exception.InnerException, out num));
         string fQEIDFromTransportError = WSManTransportManagerUtils.GetFQEIDFromTransportError(num, "ReceivePSSessionQueryForSessionFailed");
         Exception exception2 = new RuntimeException(message, exception.InnerException);
         ErrorRecord errorRecord = new ErrorRecord(exception2, fQEIDFromTransportError, ErrorCategory.InvalidOperation, connectionObject);
         base.WriteError(errorRecord);
         return;
     }
     string str3 = null;
     if (!string.IsNullOrEmpty(this.ConfigurationName))
     {
         str3 = (this.ConfigurationName.IndexOf("http://schemas.microsoft.com/powershell/", StringComparison.OrdinalIgnoreCase) != -1) ? this.ConfigurationName : ("http://schemas.microsoft.com/powershell/" + this.ConfigurationName);
     }
     foreach (Runspace runspace in runspaceArray)
     {
         if (this._stopProcessing)
         {
             return;
         }
         if (str3 != null)
         {
             WSManConnectionInfo connectionInfo = runspace.ConnectionInfo as WSManConnectionInfo;
             if ((connectionInfo != null) && !str3.Equals(connectionInfo.ShellUri, StringComparison.OrdinalIgnoreCase))
             {
                 continue;
             }
         }
         bool flag = false;
         if (!string.IsNullOrEmpty(name) && (string.Compare(name, ((RemoteRunspace) runspace).RunspacePool.RemoteRunspacePoolInternal.Name, StringComparison.OrdinalIgnoreCase) == 0))
         {
             flag = true;
         }
         else if (instanceId.Equals(runspace.InstanceId))
         {
             flag = true;
         }
         if (flag && base.ShouldProcess(((RemoteRunspace) runspace).Name, "Receive"))
         {
             Exception exception3;
             PSSession item = base.RunspaceRepository.GetItem(runspace.InstanceId);
             PSSession session2 = this.ConnectSession(item, out exception3);
             if (session2 != null)
             {
                 base.RunspaceRepository.AddOrReplace(session2);
                 PSRemotingJob job = this.FindJobForSession(session2);
                 if (this.OutTarget == Microsoft.PowerShell.Commands.OutTarget.Host)
                 {
                     this.ConnectSessionToHost(session2, job);
                     return;
                 }
                 this.ConnectSessionToJob(session2, job);
                 return;
             }
             PSSession session = new PSSession(runspace as RemoteRunspace);
             session2 = this.ConnectSession(session, out exception3);
             if (session2 != null)
             {
                 if (item != null)
                 {
                     session2 = item.InsertRunspace(session2.Runspace as RemoteRunspace) ? item : session2;
                 }
                 base.RunspaceRepository.AddOrReplace(session2);
                 if (this.OutTarget == Microsoft.PowerShell.Commands.OutTarget.Job)
                 {
                     this.ConnectSessionToJob(session2, null);
                     return;
                 }
                 this.ConnectSessionToHost(session2, null);
                 return;
             }
             string str4 = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeConnected, session.Name);
             base.WriteError(new ErrorRecord(new ArgumentException(str4, exception3), "ReceivePSSessionCannotConnectSession", ErrorCategory.InvalidOperation, session));
             return;
         }
     }
 }
Beispiel #28
0
        private bool CheckForDebugMode(PSSession session, bool monitorAvailabilityChange)
        {
            RemoteRunspace remoteRunspace = session.Runspace as RemoteRunspace;
            if (remoteRunspace.RunspaceAvailability == RunspaceAvailability.RemoteDebug)
            {
                DisconnectAndStopRunningCmds(remoteRunspace);
                WriteDebugStopWarning();
                return true;
            }

            if (monitorAvailabilityChange)
            {
                // Monitor runspace availability transition to RemoteDebug
                remoteRunspace.AvailabilityChanged += HandleRunspaceAvailabilityChanged;
            }

            return false;
        }
 private PSSession TryGetSessionFromServer(PSSession session)
 {
     if (session.Runspace is RemoteRunspace)
     {
         RemoteRunspace remoteRunspace = null;
         foreach (Runspace runspace2 in Runspace.GetRunspaces(session.Runspace.ConnectionInfo, base.Host, QueryRunspaces.BuiltInTypesTable))
         {
             if (runspace2.InstanceId == session.Runspace.InstanceId)
             {
                 remoteRunspace = runspace2 as RemoteRunspace;
                 break;
             }
         }
         if (remoteRunspace != null)
         {
             session = session.InsertRunspace(remoteRunspace) ? session : new PSSession(remoteRunspace);
             return session;
         }
     }
     return null;
 }
Beispiel #30
0
        /// <summary>
        /// Connects session, retrieves command output data and writes to host.
        /// </summary>
        /// <param name="session">PSSession object.</param>
        /// <param name="job">Job object associated with session.</param>
        private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null)
        {
            RemoteRunspace remoteRunspace = session.Runspace as RemoteRunspace;
            Dbg.Assert(remoteRunspace != null, "PS sessions can only contain RemoteRunspace type.");

            if (job != null)
            {
                // If we have a job object associated with the session then this means
                // the user explicitly chose to connect and return data synchronously.

                // Reconnect the job object and stream data to host.
                lock (_syncObject) { _job = job; _stopPipelineReceive = new ManualResetEvent(false); }
                using (_stopPipelineReceive)
                using (job)
                {
                    Job childJob = job.ChildJobs[0];
                    job.ConnectJobs();
                    if (CheckForDebugMode(session, true)) { return; }
                    do
                    {
                        // Retrieve and display results from child job as they become
                        // available.
                        int index = WaitHandle.WaitAny(new WaitHandle[] {
                            _stopPipelineReceive,
                            childJob.Results.WaitHandle });

                        foreach (var result in childJob.ReadAll())
                        {
                            if (result != null)
                            {
                                result.WriteStreamObject(this);
                            }
                        }

                        if (index == 0)
                        {
                            WriteDebugStopWarning();
                            return;
                        }
                    }
                    while (!job.IsFinishedState(job.JobStateInfo.State));
                }
                lock (_syncObject) { _job = null; _stopPipelineReceive = null; }

                return;
            }

            // Otherwise this must be a new disconnected session object that has a running command 
            // associated with it.
            if (remoteRunspace.RemoteCommand == null)
            {
                // There is no associated running command for this runspace, so we cannot proceed.
                // Check to see if session is in debug mode.
                CheckForDebugMode(session, false);
                return;
            }

            // Create a RemotePipeline object for this command and attempt to connect.
            lock (_syncObject)
            {
                _remotePipeline = (RemotePipeline)session.Runspace.CreateDisconnectedPipeline();
                _stopPipelineReceive = new ManualResetEvent(false);
            }
            using (_stopPipelineReceive)
            {
                using (_remotePipeline)
                {
                    // Connect to remote running command.
                    ManualResetEvent pipelineConnectedEvent = new ManualResetEvent(false);
                    using (pipelineConnectedEvent)
                    {
                        _remotePipeline.StateChanged += (sender, args) =>
                            {
                                if (pipelineConnectedEvent != null &&
                                    (args.PipelineStateInfo.State == PipelineState.Running ||
                                     args.PipelineStateInfo.State == PipelineState.Stopped ||
                                     args.PipelineStateInfo.State == PipelineState.Failed))
                                {
                                    pipelineConnectedEvent.Set();
                                }
                            };
                        _remotePipeline.ConnectAsync();
                        pipelineConnectedEvent.WaitOne();
                    }
                    pipelineConnectedEvent = null;

                    if (CheckForDebugMode(session, true)) { return; }

                    // Wait for remote command to complete, while writing any available data.
                    while (!_remotePipeline.Output.EndOfPipeline)
                    {
                        if (_stopProcessing)
                        {
                            break;
                        }

                        int index = WaitHandle.WaitAny(new WaitHandle[] {
                            _stopPipelineReceive,
                            _remotePipeline.Output.WaitHandle });

                        if (index == 0)
                        {
                            WriteDebugStopWarning();
                            return;
                        }

                        while (_remotePipeline.Output.Count > 0)
                        {
                            if (_stopProcessing)
                            {
                                break;
                            }

                            PSObject psObject = _remotePipeline.Output.Read();
                            WriteRemoteObject(psObject, session);
                        }
                    }

                    // Write pipeline object errors.
                    if (_remotePipeline.Error.Count > 0)
                    {
                        while (!_remotePipeline.Error.EndOfPipeline)
                        {
                            object errorObj = _remotePipeline.Error.Read();
                            if (errorObj is Collection<ErrorRecord>)
                            {
                                Collection<ErrorRecord> errorCollection = (Collection<ErrorRecord>)errorObj;
                                foreach (ErrorRecord errorRecord in errorCollection)
                                {
                                    WriteError(errorRecord);
                                }
                            }
                            else if (errorObj is ErrorRecord)
                            {
                                WriteError((ErrorRecord)errorObj);
                            }
                            else
                            {
                                Dbg.Assert(false, "Objects in pipeline Error collection must be ErrorRecord type.");
                            }
                        }
                    }

                    // Wait for pipeline to finish.
                    int wIndex = WaitHandle.WaitAny(new WaitHandle[] {
                            _stopPipelineReceive,
                            _remotePipeline.PipelineFinishedEvent });

                    if (wIndex == 0)
                    {
                        WriteDebugStopWarning();
                        return;
                    }

                    // Set the runspace RemoteCommand to null.  It is not needed anymore and it
                    // allows the runspace to become available after pipeline completes.
                    remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.ConnectCommands = null;

                    // Check for any terminating errors to report.
                    if (_remotePipeline.PipelineStateInfo.State == PipelineState.Failed)
                    {
                        Exception reason = _remotePipeline.PipelineStateInfo.Reason;
                        string msg;
                        if (reason != null && !string.IsNullOrEmpty(reason.Message))
                        {
                            msg = StringUtil.Format(RemotingErrorIdStrings.PipelineFailedWithReason, reason.Message);
                        }
                        else
                        {
                            msg = RemotingErrorIdStrings.PipelineFailedWithoutReason;
                        }

                        ErrorRecord errorRecord = new ErrorRecord(new RuntimeException(msg, reason),
                                                            "ReceivePSSessionPipelineFailed",
                                                            ErrorCategory.OperationStopped,
                                                            _remotePipeline
                                                            );

                        WriteError(errorRecord);
                    }
                }
            }
            lock (_syncObject) { _remotePipeline = null; _stopPipelineReceive = null; }
        }
 private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null)
 {
     RemoteRunspace runspace = session.Runspace as RemoteRunspace;
     if (job != null)
     {
         lock (this._syncObject)
         {
             this._job = job;
         }
         using (job)
         {
             Job job2 = job.ChildJobs[0];
             job.ConnectJobs();
             do
             {
                 job2.Results.WaitHandle.WaitOne();
                 foreach (PSStreamObject obj2 in job2.ReadAll())
                 {
                     if (obj2 != null)
                     {
                         obj2.WriteStreamObject(this, false);
                     }
                 }
             }
             while (!job.IsFinishedState(job.JobStateInfo.State));
         }
         lock (this._syncObject)
         {
             this._job = null;
         }
     }
     else if (runspace.RemoteCommand != null)
     {
         lock (this._syncObject)
         {
             this._remotePipeline = (RemotePipeline) session.Runspace.CreateDisconnectedPipeline();
         }
         using (this._remotePipeline)
         {
             this._remotePipeline.ConnectAsync();
             runspace.RunspacePool.RemoteRunspacePoolInternal.ConnectCommands = null;
             while (!this._remotePipeline.Output.EndOfPipeline)
             {
                 if (this._stopProcessing)
                 {
                     break;
                 }
                 this._remotePipeline.Output.WaitHandle.WaitOne();
                 while (this._remotePipeline.Output.Count > 0)
                 {
                     if (this._stopProcessing)
                     {
                         continue;
                     }
                     PSObject psObject = this._remotePipeline.Output.Read();
                     this.WriteRemoteObject(psObject, session);
                 }
             }
             if (this._remotePipeline.Error.Count > 0)
             {
                 while (!this._remotePipeline.Error.EndOfPipeline)
                 {
                     object obj4 = this._remotePipeline.Error.Read();
                     if (obj4 is Collection<ErrorRecord>)
                     {
                         Collection<ErrorRecord> collection = (Collection<ErrorRecord>) obj4;
                         foreach (ErrorRecord record in collection)
                         {
                             base.WriteError(record);
                         }
                     }
                     else if (obj4 is ErrorRecord)
                     {
                         base.WriteError((ErrorRecord) obj4);
                     }
                 }
             }
             this._remotePipeline.PipelineFinishedEvent.WaitOne();
             if (this._remotePipeline.PipelineStateInfo.State == PipelineState.Failed)
             {
                 string pipelineFailedWithoutReason;
                 Exception reason = this._remotePipeline.PipelineStateInfo.Reason;
                 if ((reason != null) && !string.IsNullOrEmpty(reason.Message))
                 {
                     pipelineFailedWithoutReason = StringUtil.Format(RemotingErrorIdStrings.PipelineFailedWithReason, reason.Message);
                 }
                 else
                 {
                     pipelineFailedWithoutReason = RemotingErrorIdStrings.PipelineFailedWithoutReason;
                 }
                 ErrorRecord errorRecord = new ErrorRecord(new RuntimeException(pipelineFailedWithoutReason, reason), "ReceivePSSessionPipelineFailed", ErrorCategory.OperationStopped, this._remotePipeline);
                 base.WriteError(errorRecord);
             }
         }
         lock (this._syncObject)
         {
             this._remotePipeline = null;
         }
     }
 }
Beispiel #32
0
        private bool ValidateIdleTimeout(PSSession session)
        {
            int idleTimeout = session.Runspace.ConnectionInfo.IdleTimeout;
            int maxIdleTimeout = session.Runspace.ConnectionInfo.MaxIdleTimeout;
            int minIdleTimeout = BaseTransportManager.MinimumIdleTimeout;

            if (idleTimeout != BaseTransportManager.UseServerDefaultIdleTimeout &&
                (idleTimeout > maxIdleTimeout || idleTimeout < minIdleTimeout))
            {
                string msg = StringUtil.Format(RemotingErrorIdStrings.CannotDisconnectSessionWithInvalidIdleTimeout,
                    session.Name, idleTimeout / 1000, maxIdleTimeout / 1000, minIdleTimeout / 1000);
                ErrorRecord errorRecord = new ErrorRecord(new RuntimeException(msg),
                    "CannotDisconnectSessionWithInvalidIdleTimeout", ErrorCategory.InvalidArgument, session);
                WriteError(errorRecord);

                return false;
            }

            return true;
        }