internal Collection <PSSession> GetDisconnectedSessions(Collection <WSManConnectionInfo> connectionInfos, PSHost host, ObjectStream stream, RunspaceRepository runspaceRepository, int throttleLimit, SessionFilterState filterState, Guid[] matchIds, string[] matchNames, string configurationName) { Collection <PSSession> collection = new Collection <PSSession>(); foreach (WSManConnectionInfo info in connectionInfos) { Runspace[] runspaceArray = null; try { runspaceArray = Runspace.GetRunspaces(info, host, BuiltInTypesTable); } catch (RuntimeException exception) { if (!(exception.InnerException is InvalidOperationException)) { throw; } if ((stream.ObjectWriter != null) && stream.ObjectWriter.IsOpen) { int num; string message = StringUtil.Format(RemotingErrorIdStrings.QueryForRunspacesFailed, info.ComputerName, ExtractMessage(exception.InnerException, out num)); string fQEIDFromTransportError = WSManTransportManagerUtils.GetFQEIDFromTransportError(num, "RemotePSSessionQueryFailed"); Exception exception2 = new RuntimeException(message, exception.InnerException); ErrorRecord errorRecord = new ErrorRecord(exception2, fQEIDFromTransportError, ErrorCategory.InvalidOperation, info); stream.ObjectWriter.Write(errorRecord); /* * stream.ObjectWriter.Write(delegate (Cmdlet cmdlet) { * cmdlet.WriteError(errorRecord); * }); */ } } if (this.stopProcessing) { break; } if (runspaceArray != null) { string str3 = null; if (!string.IsNullOrEmpty(configurationName)) { str3 = (configurationName.IndexOf("http://schemas.microsoft.com/powershell/", StringComparison.OrdinalIgnoreCase) != -1) ? configurationName : ("http://schemas.microsoft.com/powershell/" + configurationName); } foreach (Runspace runspace in runspaceArray) { if (str3 != null) { WSManConnectionInfo connectionInfo = runspace.ConnectionInfo as WSManConnectionInfo; if ((connectionInfo != null) && !str3.Equals(connectionInfo.ShellUri, StringComparison.OrdinalIgnoreCase)) { continue; } } PSSession item = null; if (runspaceRepository != null) { item = runspaceRepository.GetItem(runspace.InstanceId); } if ((item != null) && UseExistingRunspace(item.Runspace, runspace)) { if (this.TestRunspaceState(item.Runspace, filterState)) { collection.Add(item); } } else if (this.TestRunspaceState(runspace, filterState)) { collection.Add(new PSSession(runspace as RemoteRunspace)); } } } } if ((matchIds != null) && (collection.Count > 0)) { Collection <PSSession> collection2 = new Collection <PSSession>(); foreach (Guid guid in matchIds) { bool flag = false; foreach (PSSession session2 in collection) { if (this.stopProcessing) { break; } if (session2.Runspace.InstanceId.Equals(guid)) { flag = true; collection2.Add(session2); break; } } if ((!flag && (stream.ObjectWriter != null)) && stream.ObjectWriter.IsOpen) { Exception exception3 = new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.SessionIdMatchFailed, guid)); ErrorRecord errorRecord = new ErrorRecord(exception3, "PSSessionIdMatchFail", ErrorCategory.InvalidOperation, guid); stream.ObjectWriter.Write(errorRecord); /* * stream.ObjectWriter.Write(delegate (Cmdlet cmdlet) { * cmdlet.WriteError(errorRecord); * }); */ } } return(collection2); } if ((matchNames == null) || (collection.Count <= 0)) { return(collection); } Collection <PSSession> collection3 = new Collection <PSSession>(); foreach (string str5 in matchNames) { WildcardPattern pattern = new WildcardPattern(str5, WildcardOptions.IgnoreCase); bool flag2 = false; foreach (PSSession session3 in collection) { if (this.stopProcessing) { break; } if (pattern.IsMatch(((RemoteRunspace)session3.Runspace).RunspacePool.RemoteRunspacePoolInternal.Name)) { flag2 = true; collection3.Add(session3); } } if ((!flag2 && (stream.ObjectWriter != null)) && stream.ObjectWriter.IsOpen) { Exception exception4 = new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.SessionNameMatchFailed, str5)); ErrorRecord errorRecord = new ErrorRecord(exception4, "PSSessionNameMatchFail", ErrorCategory.InvalidOperation, str5); stream.ObjectWriter.Write(errorRecord); /* * stream.ObjectWriter.Write(delegate (Cmdlet cmdlet) { * cmdlet.WriteError(errorRecord); * }); */ } } return(collection3); }
/// <summary> /// Helper function used for opening a runspace /// </summary> private void DoOpenHelper() { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } bool startLifeCycleEventWritten = false; s_runspaceInitTracer.WriteLine("begin open runspace"); try { _transcriptionData = new TranscriptionData(); if (InitialSessionState != null) { // All ISS-based configuration of the engine itself is done by AutomationEngine, // which calls InitialSessionState.Bind(). Anything that doesn't // require an active and open runspace should be done in ISS.Bind() _engine = new AutomationEngine(Host, null, InitialSessionState); } else { _engine = new AutomationEngine(Host, RunspaceConfiguration, null); } _engine.Context.CurrentRunspace = this; //Log engine for start of engine life MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Available); startLifeCycleEventWritten = true; _commandFactory = new CommandFactory(_engine.Context); _history = new History(_engine.Context); _jobRepository = new JobRepository(); _jobManager = new JobManager(); _runspaceRepository = new RunspaceRepository(); s_runspaceInitTracer.WriteLine("initializing built-in aliases and variable information"); InitializeDefaults(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); s_runspaceInitTracer.WriteLine("Runspace open failed"); //Log engine health event LogEngineHealthEvent(exception); //Log engine for end of engine life if (startLifeCycleEventWritten) { Dbg.Assert(_engine.Context != null, "if startLifeCycleEventWritten is true, ExecutionContext must be present"); MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Stopped); } //Open failed. Set the RunspaceState to Broken. SetRunspaceState(RunspaceState.Broken, exception); //Raise the event RaiseRunspaceStateEvents(); //Rethrow the exception. For asynchronous execution, //OpenThreadProc will catch it. For synchronous execution //caller of open will catch it. throw; } SetRunspaceState(RunspaceState.Opened); RunspaceOpening.Set(); //Raise the event RaiseRunspaceStateEvents(); s_runspaceInitTracer.WriteLine("runspace opened successfully"); // Now do initial state configuration that requires an active runspace if (InitialSessionState != null) { Exception initError = InitialSessionState.BindRunspace(this, s_runspaceInitTracer); if (initError != null) { // Log engine health event LogEngineHealthEvent(initError); // Log engine for end of engine life Debug.Assert(_engine.Context != null, "if startLifeCycleEventWritten is true, ExecutionContext must be present"); MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Stopped); // Open failed. Set the RunspaceState to Broken. SetRunspaceState(RunspaceState.Broken, initError); // Raise the event RaiseRunspaceStateEvents(); // Throw the exception. For asynchronous execution, // OpenThreadProc will catch it. For synchronous execution // caller of open will catch it. throw initError; } } TelemetryAPI.ReportLocalSessionCreated(InitialSessionState, TranscriptionData); }
internal Collection<PSSession> GetDisconnectedSessions(Collection<WSManConnectionInfo> connectionInfos, PSHost host, ObjectStream stream, RunspaceRepository runspaceRepository, int throttleLimit, SessionFilterState filterState, Guid[] matchIds, string[] matchNames, string configurationName) { Collection<PSSession> collection = new Collection<PSSession>(); foreach (WSManConnectionInfo info in connectionInfos) { Runspace[] runspaceArray = null; try { runspaceArray = Runspace.GetRunspaces(info, host, BuiltInTypesTable); } catch (RuntimeException exception) { if (!(exception.InnerException is InvalidOperationException)) { throw; } if ((stream.ObjectWriter != null) && stream.ObjectWriter.IsOpen) { int num; string message = StringUtil.Format(RemotingErrorIdStrings.QueryForRunspacesFailed, info.ComputerName, ExtractMessage(exception.InnerException, out num)); string fQEIDFromTransportError = WSManTransportManagerUtils.GetFQEIDFromTransportError(num, "RemotePSSessionQueryFailed"); Exception exception2 = new RuntimeException(message, exception.InnerException); ErrorRecord errorRecord = new ErrorRecord(exception2, fQEIDFromTransportError, ErrorCategory.InvalidOperation, info); stream.ObjectWriter.Write(errorRecord); /* stream.ObjectWriter.Write(delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }); */ } } if (this.stopProcessing) { break; } if (runspaceArray != null) { string str3 = null; if (!string.IsNullOrEmpty(configurationName)) { str3 = (configurationName.IndexOf("http://schemas.microsoft.com/powershell/", StringComparison.OrdinalIgnoreCase) != -1) ? configurationName : ("http://schemas.microsoft.com/powershell/" + configurationName); } foreach (Runspace runspace in runspaceArray) { if (str3 != null) { WSManConnectionInfo connectionInfo = runspace.ConnectionInfo as WSManConnectionInfo; if ((connectionInfo != null) && !str3.Equals(connectionInfo.ShellUri, StringComparison.OrdinalIgnoreCase)) { continue; } } PSSession item = null; if (runspaceRepository != null) { item = runspaceRepository.GetItem(runspace.InstanceId); } if ((item != null) && UseExistingRunspace(item.Runspace, runspace)) { if (this.TestRunspaceState(item.Runspace, filterState)) { collection.Add(item); } } else if (this.TestRunspaceState(runspace, filterState)) { collection.Add(new PSSession(runspace as RemoteRunspace)); } } } } if ((matchIds != null) && (collection.Count > 0)) { Collection<PSSession> collection2 = new Collection<PSSession>(); foreach (Guid guid in matchIds) { bool flag = false; foreach (PSSession session2 in collection) { if (this.stopProcessing) { break; } if (session2.Runspace.InstanceId.Equals(guid)) { flag = true; collection2.Add(session2); break; } } if ((!flag && (stream.ObjectWriter != null)) && stream.ObjectWriter.IsOpen) { Exception exception3 = new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.SessionIdMatchFailed, guid)); ErrorRecord errorRecord = new ErrorRecord(exception3, "PSSessionIdMatchFail", ErrorCategory.InvalidOperation, guid); stream.ObjectWriter.Write(errorRecord); /* stream.ObjectWriter.Write(delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }); */ } } return collection2; } if ((matchNames == null) || (collection.Count <= 0)) { return collection; } Collection<PSSession> collection3 = new Collection<PSSession>(); foreach (string str5 in matchNames) { WildcardPattern pattern = new WildcardPattern(str5, WildcardOptions.IgnoreCase); bool flag2 = false; foreach (PSSession session3 in collection) { if (this.stopProcessing) { break; } if (pattern.IsMatch(((RemoteRunspace) session3.Runspace).RunspacePool.RemoteRunspacePoolInternal.Name)) { flag2 = true; collection3.Add(session3); } } if ((!flag2 && (stream.ObjectWriter != null)) && stream.ObjectWriter.IsOpen) { Exception exception4 = new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.SessionNameMatchFailed, str5)); ErrorRecord errorRecord = new ErrorRecord(exception4, "PSSessionNameMatchFail", ErrorCategory.InvalidOperation, str5); stream.ObjectWriter.Write(errorRecord); /* stream.ObjectWriter.Write(delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }); */ } } return collection3; }
protected override void Dispose(bool disposing) { try { if (_disposed) { return; } lock (SyncRoot) { if (_disposed) { return; } _disposed = true; } if (disposing) { Close(); _engine = null; _history = null; _transcriptionData = null; _jobManager = null; _jobRepository = null; _runspaceRepository = null; if (RunspaceOpening != null) { RunspaceOpening.Dispose(); RunspaceOpening = null; } // Dispose the event manager if (this.ExecutionContext != null && this.ExecutionContext.Events != null) { try { this.ExecutionContext.Events.Dispose(); } catch (ObjectDisposedException) { ; } } } } finally { base.Dispose(disposing); } }
/// <summary> /// Queries all remote computers specified in collection of WSManConnectionInfo objects /// and returns disconnected PSSession objects ready for connection to server. /// Returned sessions can be matched to Guids or Names. /// </summary> /// <param name="connectionInfos">Collection of WSManConnectionInfo objects.</param> /// <param name="host">Host for PSSession objects.</param> /// <param name="stream">Out stream object.</param> /// <param name="runspaceRepository">Runspace repository.</param> /// <param name="throttleLimit">Throttle limit.</param> /// <param name="filterState">Runspace state filter value.</param> /// <param name="matchIds">Array of session Guids to match to.</param> /// <param name="matchNames">Array of session Names to match to.</param> /// <param name="configurationName">Configuration name to match to.</param> /// <returns>Collection of disconnected PSSession objects.</returns> internal Collection<PSSession> GetDisconnectedSessions(Collection<WSManConnectionInfo> connectionInfos, PSHost host, ObjectStream stream, RunspaceRepository runspaceRepository, int throttleLimit, SessionFilterState filterState, Guid[] matchIds, string[] matchNames, string configurationName) { Collection<PSSession> filteredPSSesions = new Collection<PSSession>(); // Create a query operation for each connection information object. foreach (WSManConnectionInfo connectionInfo in connectionInfos) { Runspace[] runspaces = null; try { runspaces = Runspace.GetRunspaces(connectionInfo, host, BuiltInTypesTable); } catch (System.Management.Automation.RuntimeException e) { if (e.InnerException is InvalidOperationException) { // The Get-WSManInstance cmdlet used to query remote computers for runspaces will throw // an Invalid Operation (inner) exception if the connectInfo object is invalid, including // invalid computer names. // We don't want to propagate the exception so just write error here. if (stream.ObjectWriter != null && stream.ObjectWriter.IsOpen) { int errorCode; string msg = StringUtil.Format(RemotingErrorIdStrings.QueryForRunspacesFailed, connectionInfo.ComputerName, ExtractMessage(e.InnerException, out errorCode)); string FQEID = WSManTransportManagerUtils.GetFQEIDFromTransportError(errorCode, "RemotePSSessionQueryFailed"); Exception reason = new RuntimeException(msg, e.InnerException); ErrorRecord errorRecord = new ErrorRecord(reason, FQEID, ErrorCategory.InvalidOperation, connectionInfo); stream.ObjectWriter.Write((Action<Cmdlet>)(cmdlet => cmdlet.WriteError(errorRecord))); } } else { throw; } } if (_stopProcessing) { break; } // Add all runspaces meeting filter criteria to collection. if (runspaces != null) { // 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; } foreach (Runspace runspace in runspaces) { // 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; } } // Check the repository for an existing viable PSSession for // this runspace (based on instanceId). Use the existing // local runspace instead of the one returned from the server // query. PSSession existingPSSession = null; if (runspaceRepository != null) { existingPSSession = runspaceRepository.GetItem(runspace.InstanceId); } if (existingPSSession != null && UseExistingRunspace(existingPSSession.Runspace, runspace)) { if (TestRunspaceState(existingPSSession.Runspace, filterState)) { filteredPSSesions.Add(existingPSSession); } } else if (TestRunspaceState(runspace, filterState)) { filteredPSSesions.Add(new PSSession(runspace as RemoteRunspace)); } } } } // Return only PSSessions that match provided Ids or Names. if ((matchIds != null) && (filteredPSSesions.Count > 0)) { Collection<PSSession> matchIdsSessions = new Collection<PSSession>(); foreach (Guid id in matchIds) { bool matchFound = false; foreach (PSSession psSession in filteredPSSesions) { if (_stopProcessing) { break; } if (psSession.Runspace.InstanceId.Equals(id)) { matchFound = true; matchIdsSessions.Add(psSession); break; } } if (!matchFound && stream.ObjectWriter != null && stream.ObjectWriter.IsOpen) { string msg = StringUtil.Format(RemotingErrorIdStrings.SessionIdMatchFailed, id); Exception reason = new RuntimeException(msg); ErrorRecord errorRecord = new ErrorRecord(reason, "PSSessionIdMatchFail", ErrorCategory.InvalidOperation, id); stream.ObjectWriter.Write((Action<Cmdlet>)(cmdlet => cmdlet.WriteError(errorRecord))); } } // Return all found sessions. return matchIdsSessions; } else if ((matchNames != null) && (filteredPSSesions.Count > 0)) { Collection<PSSession> matchNamesSessions = new Collection<PSSession>(); foreach (string name in matchNames) { WildcardPattern namePattern = WildcardPattern.Get(name, WildcardOptions.IgnoreCase); bool matchFound = false; foreach (PSSession psSession in filteredPSSesions) { if (_stopProcessing) { break; } if (namePattern.IsMatch(((RemoteRunspace)psSession.Runspace).RunspacePool.RemoteRunspacePoolInternal.Name)) { matchFound = true; matchNamesSessions.Add(psSession); } } if (!matchFound && stream.ObjectWriter != null && stream.ObjectWriter.IsOpen) { string msg = StringUtil.Format(RemotingErrorIdStrings.SessionNameMatchFailed, name); Exception reason = new RuntimeException(msg); ErrorRecord errorRecord = new ErrorRecord(reason, "PSSessionNameMatchFail", ErrorCategory.InvalidOperation, name); stream.ObjectWriter.Write((Action<Cmdlet>)(cmdlet => cmdlet.WriteError(errorRecord))); } } return matchNamesSessions; } else { // Return all collected sessions. return filteredPSSesions; } }