/// <summary> /// Constructor which creates a RunspacePool using the /// supplied <paramref name="connectionInfo"/>, <paramref name="minRunspaces"/> /// and <paramref name="maxRunspaces"/> /// </summary> /// <param name="maxRunspaces"> /// The maximum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="minRunspaces"> /// The minimum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="typeTable"> /// The TypeTable to use while deserializing/serializing remote objects. /// TypeTable has the following information used by serializer: /// 1. SerializationMethod /// 2. SerializationDepth /// 3. SpecificSerializationProperties /// TypeTable has the following information used by deserializer: /// 1. TargetTypeForDeserialization /// 2. TypeConverter /// </param> /// <param name="host">Host associated with this runspacepool</param> /// <param name="applicationArguments"> /// Application arguments the server can see in <see cref="System.Management.Automation.Remoting.PSSenderInfo.ApplicationArguments"/> /// </param> /// <param name="connectionInfo">The RunspaceConnectionInfo object /// which identifies this runspace pools connection to the server /// </param> /// <param name="name">Session name.</param> /// <exception cref="ArgumentException"> /// Maximum runspaces is less than 1. /// Minimum runspaces is less than 1. /// </exception> /// <exception cref="ArgumentException"> /// ConnectionInfo specified is null /// </exception> internal RemoteRunspacePoolInternal(int minRunspaces, int maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo, string name = null) : base(minRunspaces, maxRunspaces) { if (connectionInfo == null) { throw PSTraceSource.NewArgumentNullException("WSManConnectionInfo"); } PSEtwLog.LogOperationalVerbose(PSEventId.RunspacePoolConstructor, PSOpcode.Constructor, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, instanceId.ToString(), minPoolSz.ToString(CultureInfo.InvariantCulture), maxPoolSz.ToString(CultureInfo.InvariantCulture)); _connectionInfo = connectionInfo.InternalCopy(); this.host = host; ApplicationArguments = applicationArguments; AvailableForConnection = false; DispatchTable = new DispatchTable<object>(); _runningPowerShells = new System.Collections.Concurrent.ConcurrentStack<PowerShell>(); if (!string.IsNullOrEmpty(name)) { this.Name = name; } CreateDSHandler(typeTable); }
internal RemoteRunspace(System.Management.Automation.Runspaces.RunspacePool runspacePool) { this._runningPipelines = new ArrayList(); this._syncRoot = new object(); this._runspaceStateInfo = new System.Management.Automation.Runspaces.RunspaceStateInfo(RunspaceState.BeforeOpen); this._version = PSVersionInfo.PSVersion; this._runspaceEventQueue = new Queue <RunspaceEventQueueItem>(); this.id = -1; if ((runspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Disconnected) || !(runspacePool.ConnectionInfo is WSManConnectionInfo)) { throw PSTraceSource.NewInvalidOperationException("RunspaceStrings", "InvalidRunspacePool", new object[0]); } this._runspacePool = runspacePool; this._runspacePool.RemoteRunspacePoolInternal.SetMinRunspaces(1); this._runspacePool.RemoteRunspacePoolInternal.SetMaxRunspaces(1); this._connectionInfo = ((WSManConnectionInfo)runspacePool.ConnectionInfo).Copy(); this.SetRunspaceState(RunspaceState.Disconnected, null); this._runspaceAvailability = this._runspacePool.RemoteRunspacePoolInternal.AvailableForConnection ? System.Management.Automation.Runspaces.RunspaceAvailability.None : System.Management.Automation.Runspaces.RunspaceAvailability.Busy; this.SetEventHandlers(); PSEtwLog.SetActivityIdForCurrentThread(base.InstanceId); PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceConstructor, PSOpcode.Constructor, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, new object[] { base.InstanceId.ToString() }); }
internal RemoteRunspacePoolInternal( int minRunspaces, int maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo) : base(minRunspaces, maxRunspaces) { using (RemoteRunspacePoolInternal.tracer.TraceConstructor((object)this)) { if (connectionInfo == null) { throw RemoteRunspacePoolInternal.tracer.NewArgumentNullException("WSManConnectionInfo"); } this.etwTracer.OperationalChannel.WriteVerbose(PSEventId.RunspacePoolConstructor, PSOpcode.Constructor, PSTask.CreateRunspace, (object)this.instanceId, (object)this.minPoolSz.ToString((IFormatProvider)CultureInfo.InvariantCulture), (object)this.maxPoolSz.ToString((IFormatProvider)CultureInfo.InvariantCulture)); if (connectionInfo is WSManConnectionInfo) { this.connectionInfo = (RunspaceConnectionInfo)((WSManConnectionInfo)connectionInfo).Copy(); } else if (connectionInfo is NewProcessConnectionInfo) { this.connectionInfo = (RunspaceConnectionInfo)((NewProcessConnectionInfo)connectionInfo).Copy(); } this.host = host; this.applicationArguments = applicationArguments; this.dispatchTable = new System.Management.Automation.Remoting.DispatchTable <object>(); this.dataStructureHandler = new ClientRunspacePoolDataStructureHandler(this, typeTable); this.dataStructureHandler.RemoteHostCallReceived += new EventHandler <RemoteDataEventArgs <RemoteHostCall> >(this.HandleRemoteHostCalls); this.dataStructureHandler.StateInfoReceived += new EventHandler <RemoteDataEventArgs <RunspacePoolStateInfo> >(this.HandleStateInfoReceived); this.dataStructureHandler.ApplicationPrivateDataReceived += new EventHandler <RemoteDataEventArgs <PSPrimitiveDictionary> >(this.HandleApplicationPrivateDataReceived); this.dataStructureHandler.SessionClosing += new EventHandler <RemoteDataEventArgs <Exception> >(this.HandleSessionClosing); this.dataStructureHandler.SessionClosed += new EventHandler <RemoteDataEventArgs <Exception> >(this.HandleSessionClosed); this.dataStructureHandler.SetMaxMinRunspacesResponseRecieved += new EventHandler <RemoteDataEventArgs <PSObject> >(this.HandleResponseReceived); this.dataStructureHandler.URIRedirectionReported += new EventHandler <RemoteDataEventArgs <Uri> >(this.HandleURIDirectionReported); this.dataStructureHandler.PSEventArgsReceived += new EventHandler <RemoteDataEventArgs <PSEventArgs> >(this.HandlePSEventArgsReceived); } }
internal CreateCompleteEventArgs(RunspaceConnectionInfo connectionInfo) { this._connectionInfo = connectionInfo; }
internal RemoteRunspacePoolInternal(int minRunspaces, int maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo, string name = null) : base(minRunspaces, maxRunspaces) { this.applicationPrivateDataReceived = new ManualResetEvent(false); this.friendlyName = string.Empty; if (connectionInfo == null) { throw PSTraceSource.NewArgumentNullException("WSManConnectionInfo"); } PSEtwLog.LogOperationalVerbose(PSEventId.RunspacePoolConstructor, PSOpcode.Constructor, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, new object[] { this.instanceId.ToString(), this.minPoolSz.ToString(CultureInfo.InvariantCulture), this.maxPoolSz.ToString(CultureInfo.InvariantCulture) }); if (connectionInfo is WSManConnectionInfo) { this.connectionInfo = ((WSManConnectionInfo)connectionInfo).Copy(); } else if (connectionInfo is NewProcessConnectionInfo) { this.connectionInfo = ((NewProcessConnectionInfo)connectionInfo).Copy(); } base.host = host; this.applicationArguments = applicationArguments; this.availableForConnection = false; this.dispatchTable = new DispatchTable <object>(); if (!string.IsNullOrEmpty(name)) { this.Name = name; } this.CreateDSHandler(typeTable); }
internal RemoteRunspacePoolInternal(Guid instanceId, string name, bool isDisconnected, ConnectCommandInfo[] connectCommands, RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable) : base(1, 1) { this.applicationPrivateDataReceived = new ManualResetEvent(false); this.friendlyName = string.Empty; if (connectCommands == null) { throw PSTraceSource.NewArgumentNullException("ConnectCommandInfo[]"); } if (connectionInfo == null) { throw PSTraceSource.NewArgumentNullException("WSManConnectionInfo"); } if (connectionInfo is WSManConnectionInfo) { this.connectionInfo = ((WSManConnectionInfo)connectionInfo).Copy(); } base.instanceId = instanceId; base.minPoolSz = -1; base.maxPoolSz = -1; PSEtwLog.LogOperationalVerbose(PSEventId.RunspacePoolConstructor, PSOpcode.Constructor, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, new object[] { instanceId.ToString(), this.minPoolSz.ToString(CultureInfo.InvariantCulture), this.maxPoolSz.ToString(CultureInfo.InvariantCulture) }); this.connectCommands = connectCommands; this.Name = name; base.host = host; this.dispatchTable = new DispatchTable <object>(); this.SetRunspacePoolState(new RunspacePoolStateInfo(RunspacePoolState.Disconnected, null)); this.CreateDSHandler(typeTable); this.availableForConnection = isDisconnected; }
internal PowwaSession(string sessionId, string sessionUser, RunspaceConnectionInfo connectionInfo, ClientInfo clientInfo) { EventHandler <MessageCreatedEventArgs> eventHandler = null; EventHandler <MessageCreatedEventArgs> eventHandler1 = null; EventHandler <MessageCreatedEventArgs> eventHandler2 = null; if (sessionId != null) { if (connectionInfo != null) { if (clientInfo != null) { this.Id = sessionId; this.Name = string.Empty; this.UserName = sessionUser; this.host = new PowwaHost(clientInfo); this.host.UI.RawUI.WindowTitle = connectionInfo.ComputerName; PowwaHost powwaHost = this.host; if (eventHandler == null) { eventHandler = (object sender, MessageCreatedEventArgs e) => this.OnClientMessageCreated(e); } powwaHost.MessageCreated += eventHandler; IMessageCreated uI = (IMessageCreated)this.host.UI; if (eventHandler1 == null) { eventHandler1 = (object sender, MessageCreatedEventArgs e) => this.OnClientMessageCreated(e); } uI.MessageCreated += eventHandler1; IMessageCreated rawUI = (IMessageCreated)this.host.UI.RawUI; if (eventHandler2 == null) { eventHandler2 = (object sender, MessageCreatedEventArgs e) => this.OnClientMessageCreated(e); } rawUI.MessageCreated += eventHandler2; this.Runspace = RunspaceFactory.CreateRunspace(connectionInfo, this.host, PowwaSession.TypeTableLoader.Instance.LoadDefaultTypeFiles()); this.Runspace.StateChanged += new EventHandler <RunspaceStateEventArgs>(this.OnRunspaceStateChanged); this.executingCommandPowerShell = System.Management.Automation.PowerShell.Create(); this.executingCommandPowerShell.Runspace = this.Runspace; this.executingCommandPowerShell.InvocationStateChanged += new EventHandler <PSInvocationStateChangedEventArgs>(this.OnExecutingCommandInvocationStateChanged); this.messageQueue = new MessageQueue(); this.clientRequestLock = new object(); this.cancelCommandLock = new object(); this.sessionStateLock = new object(); this.SessionKey = PowwaSession.CreateSessionKey(); this.State = PowwaSession.SessionState.Available; try { this.Runspace.Open(); } catch (Exception ex) { var stackTrace = ex.StackTrace; System.Diagnostics.Debug.WriteLine(stackTrace); } this.exec = new Microsoft.PowerShell.Executor(this.host, false, false); this.exec.OutputHandler += HandleOutputHandler; if (this.messageQueue.GetMessageCount() > 0) { this.PostClientMessage(new CommandCompletedMessage(this.GetPowerShellPrompt()), false); } return; } else { throw new ArgumentNullException("clientInfo"); } } else { throw new ArgumentNullException("connectionInfo"); } } else { throw new ArgumentNullException("sessionId"); } }
public IRunspace CreateRunspace(RunspaceConnectionInfo connectionInfo) { return(new Wrappers.Implementations.Runspace(System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo))); }
internal virtual void Redirect(Uri newUri, RunspaceConnectionInfo connectionInfo) => throw new NotImplementedException();
/// <summary> /// Create a runspacepool object in the disconnected state. /// </summary> /// <param name="instanceId">Identifies remote session to connect.</param> /// <param name="name">Friendly name for runspace pool.</param> /// <param name="isDisconnected">Indicates whether the runspacepool is disconnected.</param> /// <param name="connectCommands">Array of commands associated with this runspace pool.</param> /// <param name="connectionInfo">Connection information for remote server.</param> /// <param name="host">PSHost object.</param> /// <param name="typeTable">TypeTable for object serialization/deserialization.</param> internal RemoteRunspacePoolInternal(Guid instanceId, string name, bool isDisconnected, ConnectCommandInfo[] connectCommands, RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable) : base(1, 1) { if (instanceId == null) { throw PSTraceSource.NewArgumentNullException("RunspacePool Guid"); } if (connectCommands == null) { throw PSTraceSource.NewArgumentNullException("ConnectCommandInfo[]"); } if (connectionInfo == null) { throw PSTraceSource.NewArgumentNullException("WSManConnectionInfo"); } if (connectionInfo is WSManConnectionInfo) { _connectionInfo = connectionInfo.InternalCopy(); } else { Dbg.Assert(false, "ConnectionInfo must be WSManConnectionInfo"); } // Create the runspace pool object to have the same instanceId as the remote session. this.instanceId = instanceId; // This indicates that this is a disconnected remote runspace pool and min/max values // are currently unknown. These values will be updated once the object is connected. this.minPoolSz = -1; this.maxPoolSz = -1; PSEtwLog.LogOperationalVerbose(PSEventId.RunspacePoolConstructor, PSOpcode.Constructor, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, instanceId.ToString(), minPoolSz.ToString(CultureInfo.InvariantCulture), maxPoolSz.ToString(CultureInfo.InvariantCulture)); ConnectCommands = connectCommands; this.Name = name; this.host = host; DispatchTable = new DispatchTable<object>(); _runningPowerShells = new System.Collections.Concurrent.ConcurrentStack<PowerShell>(); // Create this object in the disconnected state. SetRunspacePoolState(new RunspacePoolStateInfo(RunspacePoolState.Disconnected, null)); CreateDSHandler(typeTable); AvailableForConnection = isDisconnected; }
internal virtual BaseClientCommandTransportManager CreateClientCommandTransportManager(RunspaceConnectionInfo connectionInfo, ClientRemotePowerShell cmd, bool noInput) { throw new NotImplementedException(); }
public PNetRunspacePool(RunspaceConnectionInfo connectionInfo) { _connectionInfo = connectionInfo; }
public PNetRunspacePool() { _connectionInfo = null; }
private string GenerateNewPSSessionOption() { StringBuilder builder = new StringBuilder("& $script:NewPSSessionOption "); RunspaceConnectionInfo connectionInfo = this.remoteRunspaceInfo.Runspace.ConnectionInfo; if (connectionInfo != null) { builder.AppendFormat(null, "-Culture '{0}' ", new object[] { CommandMetadata.EscapeSingleQuotedString(connectionInfo.Culture.ToString()) }); builder.AppendFormat(null, "-UICulture '{0}' ", new object[] { CommandMetadata.EscapeSingleQuotedString(connectionInfo.UICulture.ToString()) }); builder.AppendFormat(null, "-CancelTimeOut {0} ", new object[] { connectionInfo.CancelTimeout }); builder.AppendFormat(null, "-IdleTimeOut {0} ", new object[] { connectionInfo.IdleTimeout }); builder.AppendFormat(null, "-OpenTimeOut {0} ", new object[] { connectionInfo.OpenTimeout }); builder.AppendFormat(null, "-OperationTimeOut {0} ", new object[] { connectionInfo.OperationTimeout }); } WSManConnectionInfo wsmanConnectionInfo = this.remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; if (wsmanConnectionInfo != null) { if (!wsmanConnectionInfo.UseCompression) { builder.Append("-NoCompression "); } if (wsmanConnectionInfo.NoEncryption) { builder.Append("-NoEncryption "); } if (wsmanConnectionInfo.NoMachineProfile) { builder.Append("-NoMachineProfile "); } if (wsmanConnectionInfo.UseUTF16) { builder.Append("-UseUTF16 "); } if (wsmanConnectionInfo.SkipCACheck) { builder.Append("-SkipCACheck "); } if (wsmanConnectionInfo.SkipCNCheck) { builder.Append("-SkipCNCheck "); } if (wsmanConnectionInfo.SkipRevocationCheck) { builder.Append("-SkipRevocationCheck "); } if (wsmanConnectionInfo.MaximumReceivedDataSizePerCommand.HasValue) { builder.AppendFormat(CultureInfo.InvariantCulture, "-MaximumReceivedDataSizePerCommand {0} ", new object[] { wsmanConnectionInfo.MaximumReceivedDataSizePerCommand.Value }); } if (wsmanConnectionInfo.MaximumReceivedObjectSize.HasValue) { builder.AppendFormat(CultureInfo.InvariantCulture, "-MaximumReceivedObjectSize {0} ", new object[] { wsmanConnectionInfo.MaximumReceivedObjectSize.Value }); } builder.AppendFormat(CultureInfo.InvariantCulture, "-MaximumRedirection {0} ", new object[] { wsmanConnectionInfo.MaximumConnectionRedirectionCount }); builder.AppendFormat(CultureInfo.InvariantCulture, "-ProxyAccessType {0} ", new object[] { wsmanConnectionInfo.ProxyAccessType.ToString() }); builder.AppendFormat(CultureInfo.InvariantCulture, "-ProxyAuthentication {0} ", new object[] { wsmanConnectionInfo.ProxyAuthentication.ToString() }); builder.Append(this.GenerateProxyCredentialParameter(wsmanConnectionInfo)); } if (this.GetApplicationArguments() != null) { builder.Append("-ApplicationArguments $("); builder.Append("& $script:ImportCliXml -Path $("); builder.Append("& $script:JoinPath -Path $PSScriptRoot -ChildPath ApplicationArguments.xml"); builder.Append(")"); builder.Append(") "); } return(builder.ToString()); }
internal ClientRemoteSessionDSHandlerImpl(ClientRemoteSession session, PSRemotingCryptoHelper cryptoHelper, RunspaceConnectionInfo connectionInfo, ClientRemoteSession.URIDirectionReported uriRedirectionHandler) { if (session == null) { throw PSTraceSource.NewArgumentNullException("session"); } this._session = session; this._stateMachine = new ClientRemoteSessionDSHandlerStateMachine(); this._stateMachine.StateChanged += new EventHandler <RemoteSessionStateEventArgs>(this.HandleStateChanged); this._connectionInfo = connectionInfo; this._cryptoHelper = cryptoHelper; if (this._connectionInfo is NewProcessConnectionInfo) { this._transportManager = new OutOfProcessClientSessionTransportManager(this._session.RemoteRunspacePoolInternal.InstanceId, (NewProcessConnectionInfo)this._connectionInfo, cryptoHelper); } else { this._transportManager = new WSManClientSessionTransportManager(this._session.RemoteRunspacePoolInternal.InstanceId, (WSManConnectionInfo)this._connectionInfo, cryptoHelper, this._session.RemoteRunspacePoolInternal.Name); } this._transportManager.DataReceived += new EventHandler <RemoteDataEventArgs>(this.DispatchInputQueueData); this._transportManager.WSManTransportErrorOccured += new EventHandler <TransportErrorOccuredEventArgs>(this.HandleTransportError); this._transportManager.CloseCompleted += new EventHandler <EventArgs>(this.HandleCloseComplete); this._transportManager.DisconnectCompleted += new EventHandler <EventArgs>(this.HandleDisconnectComplete); this._transportManager.ReconnectCompleted += new EventHandler <EventArgs>(this.HandleReconnectComplete); this._transportManager.RobustConnectionNotification += new EventHandler <ConnectionStatusEventArgs>(this.HandleRobustConnectionNotification); WSManConnectionInfo info = connectionInfo as WSManConnectionInfo; if (info != null) { this.uriRedirectionHandler = uriRedirectionHandler; this.maxUriRedirectionCount = info.MaximumConnectionRedirectionCount; } }
internal override BaseClientCommandTransportManager CreateClientCommandTransportManager(RunspaceConnectionInfo connectionInfo, ClientRemotePowerShell cmd, bool noInput) { OutOfProcessClientCommandTransportManager cmdTM = new OutOfProcessClientCommandTransportManager(cmd, noInput, this, this.stdInWriter); this.AddCommandTransportManager(cmd.InstanceId, cmdTM); return(cmdTM); }
internal static RunspacePool[] GetRemoteRunspacePools(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable) { WSManConnectionInfo wsmanConnectionInfoParam = connectionInfo as WSManConnectionInfo; // Disconnect-Connect currently only supported by WSMan. if (wsmanConnectionInfoParam == null) { throw new NotSupportedException(); } List<RunspacePool> discRunspacePools = new List<RunspacePool>(); // Enumerate all runspacepools Collection<PSObject> runspaceItems = RemoteRunspacePoolEnumeration.GetRemotePools(wsmanConnectionInfoParam); foreach (PSObject rsObject in runspaceItems) { // Create a new WSMan connection info object for each returned runspace pool. WSManConnectionInfo wsmanConnectionInfo = wsmanConnectionInfoParam.Copy(); PSPropertyInfo pspShellId = rsObject.Properties["ShellId"]; PSPropertyInfo pspState = rsObject.Properties["State"]; PSPropertyInfo pspName = rsObject.Properties["Name"]; PSPropertyInfo pspResourceUri = rsObject.Properties["ResourceUri"]; if (pspShellId == null || pspState == null || pspName == null || pspResourceUri == null) { continue; } string strName = pspName.Value.ToString(); string strShellUri = pspResourceUri.Value.ToString(); bool isDisconnected = pspState.Value.ToString().Equals("Disconnected", StringComparison.OrdinalIgnoreCase); Guid shellId = Guid.Parse(pspShellId.Value.ToString()); // Filter returned items for PowerShell sessions. if (strShellUri.StartsWith(WSManNativeApi.ResourceURIPrefix, StringComparison.OrdinalIgnoreCase) == false) { continue; } // Update wsmanconnection information with server settings. UpdateWSManConnectionInfo(wsmanConnectionInfo, rsObject); // Ensure that EnableNetworkAccess property is always enabled for reconstructed runspaces. wsmanConnectionInfo.EnableNetworkAccess = true; // Compute runspace DisconnectedOn and ExpiresOn fields. if (isDisconnected) { DateTime? disconnectedOn; DateTime? expiresOn; ComputeDisconnectedOnExpiresOn(rsObject, out disconnectedOn, out expiresOn); wsmanConnectionInfo.DisconnectedOn = disconnectedOn; wsmanConnectionInfo.ExpiresOn = expiresOn; } List<ConnectCommandInfo> connectCmdInfos = new List<ConnectCommandInfo>(); // Enumerate all commands on runspace pool. Collection<PSObject> commandItems; try { commandItems = RemoteRunspacePoolEnumeration.GetRemoteCommands(shellId, wsmanConnectionInfo); } catch (CmdletInvocationException e) { if (e.InnerException != null && e.InnerException is InvalidOperationException) { // If we cannot successfully retrieve command information then this runspace // object we are building is invalid and must be skipped. continue; } throw; } foreach (PSObject cmdObject in commandItems) { PSPropertyInfo pspCommandId = cmdObject.Properties["CommandId"]; PSPropertyInfo pspCommandLine = cmdObject.Properties["CommandLine"]; if (pspCommandId == null) { Dbg.Assert(false, "Should not get an empty command Id from a remote runspace pool."); continue; } string cmdLine = (pspCommandLine != null) ? pspCommandLine.Value.ToString() : string.Empty; Guid cmdId = Guid.Parse(pspCommandId.Value.ToString()); connectCmdInfos.Add(new ConnectCommandInfo(cmdId, cmdLine)); } // At this point we don't know if the runspace pool we want to connect to has just one runspace // (a RemoteRunspace/PSSession) or multiple runspaces in its pool. We do have an array of // running command information which will indicate a runspace pool if the count is gt one. RunspacePool runspacePool = new RunspacePool(isDisconnected, shellId, strName, connectCmdInfos.ToArray(), wsmanConnectionInfo, host, typeTable); discRunspacePools.Add(runspacePool); } return discRunspacePools.ToArray(); }
/// <summary> /// Create the Runspace pool. /// For remote runspaces, load the datatypes optionally to support serialization /// For local commands, load the modules and snapins required or requested /// </summary> /// <param name="commandInfo"></param> /// <param name="pSHost"></param> /// <param name="maxRunspaces"></param> /// <param name="debugStrings"></param> /// <param name="useRemotePS"></param> /// <param name="loadAllTypedata"></param> /// <param name="modules"></param> /// <param name="modulesPath"></param> /// <param name="snapIns"></param> /// <param name="variableEntries"></param> /// <returns></returns> internal static RunspacePool CreateRunspacePool(CommandInfo commandInfo, PSHost pSHost, int maxRunspaces, out List <string> debugStrings, PSSession useRemotePS, bool loadAllTypedata, string[] modules = null, string[] modulesPath = null, string[] snapIns = null, IList <SessionStateVariableEntry> variableEntries = null) { debugStrings = new List <string>(); RunspaceConnectionInfo runspaceConnectionInfo = null; Hashtable modulePrivatedata = commandInfo.Module?.PrivateData as Hashtable; ModuleDetails moduleDetails = GetModuleDetails(commandInfo, debugStrings); //special handling for remote PSsession commands if (moduleDetails.IsFromRemotingModule || useRemotePS != null) { if (useRemotePS != null) { debugStrings.Add("Using the supplied remote PSSession"); runspaceConnectionInfo = useRemotePS.Runspace.ConnectionInfo; } else { debugStrings.Add("Using remote PSSession to execute the command"); PSObject remotepSModule = ScriptBlock.Create( string.Format("Get-Module {0}", commandInfo.ModuleName)).InvokeReturnAsIs() as PSObject; if (remotepSModule.BaseObject is PSModuleInfo remotepSModuleInfo) { PSObject remotePs = ScriptBlock.Create( string.Format("Get-PSSession | Where-Object{{$_.state -eq 'opened' -and (\"{0}\").Contains($_.ComputerName)}} | Select-Object -First 1", remotepSModuleInfo.Description)).InvokeReturnAsIs() as PSObject; if (remotePs.BaseObject is PSSession remotePSSession) { runspaceConnectionInfo = remotePSSession.Runspace.ConnectionInfo; if (modules != null || modulesPath != null) { debugStrings.Add("Modules were specified to load, but they will not be loaded as the command supplied is from a remote PSSession"); } } else { debugStrings.Add(string.Format("Command - Get-PSSession | Where-Object{{$_.state -eq 'opened' -and (\"{0}\").Contains($_.ComputerName)}} " + "| Select-Object -First 1 - was ran to find the PSSession", remotepSModuleInfo.Description)); throw new Exception("Unable to find a PSSession to use. You may try passing the PSSession to use using Parameter -UseRemotePSSession"); } } } debugStrings.Add(string.Format("Using connection info {0}", runspaceConnectionInfo.ComputerName)); TypeTable typeTable = TypeTable.LoadDefaultTypeFiles(); if (loadAllTypedata) { Collection <PSObject> typeDatas = ScriptBlock.Create("Get-TypeData").Invoke(); foreach (PSObject typeData in typeDatas) { TypeData t = (TypeData)typeData.BaseObject; try { typeTable.AddType(t); debugStrings.Add(string.Format("Added typedata{0}", t.TypeName)); } catch (Exception e) { debugStrings.Add(string.Format("Unable to add typeData {0}. Error {1}", t.TypeName, e.Message)); } } } return(RunspaceFactory.CreateRunspacePool(1, Environment.ProcessorCount, runspaceConnectionInfo, pSHost, typeTable)); } InitialSessionState iss = InitialSessionState.CreateDefault2(); List <string> modulesToLoad = new List <String>(); List <string> snapInsToLoad = new List <string>(); PSSnapInException pSSnapInException = new PSSnapInException(); if (modules?.Count() > 0) { modulesToLoad.AddRange(modules); } if (snapIns?.Count() > 0) { snapInsToLoad.AddRange(snapIns); } //Populate ISS with the snapins and modules from the moduleDetails LoadISSWithModuleDetails(moduleDetails, iss); //Load user specified snapins and modules if (modules?.Count() > 0 && modules.Contains("All", StringComparer.OrdinalIgnoreCase)) { var modulesAvailable = ScriptBlock.Create("Get-Module -ListAvailable | Select-Object -ExpandProperty Name").Invoke(); modulesToLoad.AddRange(from module in modulesAvailable select module.BaseObject as string); debugStrings.Add(string.Format("Loaded all the available modules on this computer, {0} modules found", modulesToLoad.Count)); } if (modules?.Count() > 0 && modules.Contains("Loaded", StringComparer.OrdinalIgnoreCase)) { var modulesLoaded = ScriptBlock.Create("Get-Module | Select-Object -ExpandProperty Name").Invoke(); modulesToLoad.AddRange(from module in modulesLoaded select module.BaseObject as string); debugStrings.Add(string.Format("Loaded the modules loaded on current Runspace, {0} modules found", modulesLoaded.Count)); } debugStrings.Add("Loading Modules:"); debugStrings.AddRange(modulesToLoad); iss.ImportPSModule(modulesToLoad.ToArray()); snapInsToLoad.ForEach(s => iss.ImportPSSnapIn(s, out pSSnapInException)); if (variableEntries != null) { iss.Variables.Add(variableEntries); } return(RunspaceFactory.CreateRunspacePool(1, maxRunspaces, iss, pSHost)); }
internal static RunspacePool GetRemoteRunspacePool(RunspaceConnectionInfo connectionInfo, Guid sessionId, Guid? commandId, PSHost host, TypeTable typeTable) { List<ConnectCommandInfo> connectCmdInfos = new List<ConnectCommandInfo>(); if (commandId != null) { connectCmdInfos.Add(new ConnectCommandInfo(commandId.Value, string.Empty)); } return new RunspacePool(true, sessionId, string.Empty, connectCmdInfos.ToArray(), connectionInfo, host, typeTable); }