public InvokeParallelTests() { _iss = CreateInitialSessionState(); m_runspacePool = RunspaceFactory.CreateRunspacePool(_iss); m_runspacePool.SetMaxRunspaces(10); m_runspacePool.Open(); }
internal RemoteRunspace(TypeTable typeTable, RunspaceConnectionInfo connectionInfo, PSHost host, PSPrimitiveDictionary applicationArguments, string name = null, int id = -1) { 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; PSEtwLog.SetActivityIdForCurrentThread(base.InstanceId); this._applicationArguments = applicationArguments; PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceConstructor, PSOpcode.Constructor, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, new object[] { base.InstanceId.ToString() }); if (connectionInfo is WSManConnectionInfo) { this._connectionInfo = ((WSManConnectionInfo)connectionInfo).Copy(); this._originalConnectionInfo = ((WSManConnectionInfo)connectionInfo).Copy(); } else if (connectionInfo is NewProcessConnectionInfo) { this._connectionInfo = ((NewProcessConnectionInfo)connectionInfo).Copy(); this._originalConnectionInfo = ((NewProcessConnectionInfo)connectionInfo).Copy(); } this._runspacePool = new System.Management.Automation.Runspaces.RunspacePool(1, 1, typeTable, host, applicationArguments, connectionInfo, name); this.Id = id; this.SetEventHandlers(); }
public RunspaceSettings(RunspacePool pool) : this() { if (pool == null) { return; } this.ApartmentState = pool.ApartmentState; this.CleanupInterval = pool.CleanupInterval; this.InitialSessionState = pool.InitialSessionState; this.InstanceId = pool.InstanceId; this.IsDisposed = pool.IsDisposed; this.PoolSize = pool.GetMaxRunspaces(); this.RunspacePoolAvailability = pool.RunspacePoolAvailability; this.RunspacePoolStateInfo = pool.RunspacePoolStateInfo; this.ThreadOptions = pool.ThreadOptions; }
internal ServerRunspacePoolDriver(Guid clientRunspacePoolId, int minRunspaces, int maxRunspaces, PSThreadOptions threadOptions, ApartmentState apartmentState, HostInfo hostInfo, InitialSessionState initialSessionState, PSPrimitiveDictionary applicationPrivateData, ConfigurationDataFromXML configData, AbstractServerSessionTransportManager transportManager, bool isAdministrator, RemoteSessionCapability serverCapability, Hashtable configHash) { this.serverCapability = serverCapability; System.Management.Automation.Remoting.ServerRemoteHost host = new System.Management.Automation.Remoting.ServerRemoteHost(clientRunspacePoolId, Guid.Empty, hostInfo, transportManager); this.remoteHost = host; this.configData = configData; this.configHash = configHash; this.applicationPrivateData = applicationPrivateData; this.localRunspacePool = RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces, initialSessionState, host); PSThreadOptions options = configData.ShellThreadOptions.HasValue ? configData.ShellThreadOptions.Value : PSThreadOptions.UseCurrentThread; if ((threadOptions == PSThreadOptions.Default) || (threadOptions == options)) { this.localRunspacePool.ThreadOptions = options; } else { if (!isAdministrator) { throw new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.MustBeAdminToOverrideThreadOptions, new object[0])); } this.localRunspacePool.ThreadOptions = threadOptions; } ApartmentState state = configData.ShellThreadApartmentState.HasValue ? configData.ShellThreadApartmentState.Value : ApartmentState.Unknown; if ((apartmentState == ApartmentState.Unknown) || (apartmentState == state)) { this.localRunspacePool.ApartmentState = state; } else { this.localRunspacePool.ApartmentState = apartmentState; } this.clientRunspacePoolId = clientRunspacePoolId; this.dsHandler = new ServerRunspacePoolDataStructureHandler(this, transportManager); this.localRunspacePool.StateChanged += new EventHandler <RunspacePoolStateChangedEventArgs>(this.HandleRunspacePoolStateChanged); this.localRunspacePool.ForwardEvent += new EventHandler <PSEventArgs>(this.HandleRunspacePoolForwardEvent); this.localRunspacePool.RunspaceCreated += new EventHandler <RunspaceCreatedEventArgs>(this.HandleRunspaceCreated); this.localRunspacePool.RunspaceCreated += new EventHandler <RunspaceCreatedEventArgs>(this.HandleRunspaceCreatedForTypeTable); this.dsHandler.CreateAndInvokePowerShell += new EventHandler <RemoteDataEventArgs <RemoteDataObject <PSObject> > >(this.HandleCreateAndInvokePowerShell); this.dsHandler.GetCommandMetadata += new EventHandler <RemoteDataEventArgs <RemoteDataObject <PSObject> > >(this.HandleGetCommandMetadata); this.dsHandler.HostResponseReceived += new EventHandler <RemoteDataEventArgs <RemoteHostResponse> >(this.HandleHostResponseReceived); this.dsHandler.SetMaxRunspacesReceived += new EventHandler <RemoteDataEventArgs <PSObject> >(this.HandleSetMaxRunspacesReceived); this.dsHandler.SetMinRunspacesReceived += new EventHandler <RemoteDataEventArgs <PSObject> >(this.HandleSetMinRunspacesReceived); this.dsHandler.GetAvailableRunspacesReceived += new EventHandler <RemoteDataEventArgs <PSObject> >(this.HandleGetAvailalbeRunspacesReceived); }
internal ServerRunspacePoolDriver(Guid clientRunspacePoolId, int minRunspaces, int maxRunspaces, PSThreadOptions threadOptions, ApartmentState apartmentState, HostInfo hostInfo, InitialSessionState initialSessionState, PSPrimitiveDictionary applicationPrivateData, ConfigurationDataFromXML configData, AbstractServerSessionTransportManager transportManager, bool isAdministrator, RemoteSessionCapability serverCapability, Hashtable configHash) { this.serverCapability = serverCapability; System.Management.Automation.Remoting.ServerRemoteHost host = new System.Management.Automation.Remoting.ServerRemoteHost(clientRunspacePoolId, Guid.Empty, hostInfo, transportManager); this.remoteHost = host; this.configData = configData; this.configHash = configHash; this.applicationPrivateData = applicationPrivateData; this.localRunspacePool = RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces, initialSessionState, host); PSThreadOptions options = configData.ShellThreadOptions.HasValue ? configData.ShellThreadOptions.Value : PSThreadOptions.UseCurrentThread; if ((threadOptions == PSThreadOptions.Default) || (threadOptions == options)) { this.localRunspacePool.ThreadOptions = options; } else { if (!isAdministrator) { throw new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.MustBeAdminToOverrideThreadOptions, new object[0])); } this.localRunspacePool.ThreadOptions = threadOptions; } ApartmentState state = configData.ShellThreadApartmentState.HasValue ? configData.ShellThreadApartmentState.Value : ApartmentState.Unknown; if ((apartmentState == ApartmentState.Unknown) || (apartmentState == state)) { this.localRunspacePool.ApartmentState = state; } else { this.localRunspacePool.ApartmentState = apartmentState; } this.clientRunspacePoolId = clientRunspacePoolId; this.dsHandler = new ServerRunspacePoolDataStructureHandler(this, transportManager); this.localRunspacePool.StateChanged += new EventHandler<RunspacePoolStateChangedEventArgs>(this.HandleRunspacePoolStateChanged); this.localRunspacePool.ForwardEvent += new EventHandler<PSEventArgs>(this.HandleRunspacePoolForwardEvent); this.localRunspacePool.RunspaceCreated += new EventHandler<RunspaceCreatedEventArgs>(this.HandleRunspaceCreated); this.localRunspacePool.RunspaceCreated += new EventHandler<RunspaceCreatedEventArgs>(this.HandleRunspaceCreatedForTypeTable); this.dsHandler.CreateAndInvokePowerShell += new EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>>(this.HandleCreateAndInvokePowerShell); this.dsHandler.GetCommandMetadata += new EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>>(this.HandleGetCommandMetadata); this.dsHandler.HostResponseReceived += new EventHandler<RemoteDataEventArgs<RemoteHostResponse>>(this.HandleHostResponseReceived); this.dsHandler.SetMaxRunspacesReceived += new EventHandler<RemoteDataEventArgs<PSObject>>(this.HandleSetMaxRunspacesReceived); this.dsHandler.SetMinRunspacesReceived += new EventHandler<RemoteDataEventArgs<PSObject>>(this.HandleSetMinRunspacesReceived); this.dsHandler.GetAvailableRunspacesReceived += new EventHandler<RemoteDataEventArgs<PSObject>>(this.HandleGetAvailalbeRunspacesReceived); }
internal void Close() { if (!this.isClosed) { this.isClosed = true; this.localRunspacePool.Close(); this.localRunspacePool.StateChanged -= new EventHandler <RunspacePoolStateChangedEventArgs>(this.HandleRunspacePoolStateChanged); this.localRunspacePool.ForwardEvent -= new EventHandler <PSEventArgs>(this.HandleRunspacePoolForwardEvent); this.localRunspacePool.Dispose(); this.localRunspacePool = null; if (this.rsToUseForSteppablePipeline != null) { this.rsToUseForSteppablePipeline.Close(); this.rsToUseForSteppablePipeline.Dispose(); this.rsToUseForSteppablePipeline = null; } this.Closed.SafeInvoke <EventArgs>(this, EventArgs.Empty); } }
// ---------- CONSTRUCTORS ---------- /// <summary> /// Inititalizes the PowerShellScript environment. /// </summary> /// <param name="log">An event log to log exceptions to. May be null if no exception logging is desired.</param> /// <param name="pool">A runspace pool for the scripting environment to use. May be null if a new Runspace pool is desired.</param> public PowerShellScript(EventLog.EventLog log, RunspacePool pool) { RunspacePool = null; Log = log; if (pool != null) { RunspacePool = pool; // Open the Runspace Pool so it's ready for use. if (RunspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Opened) { RunspacePool.Open(); } } else { InitializeRunspacePool(); } }
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 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() }); }
/// <summary> /// Dispose the runspace pool driver and release all its resources /// </summary> internal void Close() { if (!_isClosed) { _isClosed = true; if ((_remoteHost != null) && (_remoteHost.IsRunspacePushed)) { Runspace runspaceToDispose = _remoteHost.PushedRunspace; _remoteHost.PopRunspace(); if (runspaceToDispose != null) { runspaceToDispose.Dispose(); } } DisposeRemoteDebugger(); RunspacePool.Close(); RunspacePool.StateChanged -= new EventHandler<RunspacePoolStateChangedEventArgs>(HandleRunspacePoolStateChanged); RunspacePool.ForwardEvent -= new EventHandler<PSEventArgs>(HandleRunspacePoolForwardEvent); RunspacePool.Dispose(); RunspacePool = null; if (_rsToUseForSteppablePipeline != null) { _rsToUseForSteppablePipeline.Close(); _rsToUseForSteppablePipeline.Dispose(); _rsToUseForSteppablePipeline = null; } Closed.SafeInvoke(this, EventArgs.Empty); } }
/// <summary> /// Creates a new pool of Runspaces for this script to utilize. /// </summary> public void InitializeRunspacePool() { RunspacePool = RunspaceFactory.CreateRunspacePool(); // Open the Runspace Pool so it's ready for use. RunspacePool.Open(); }
internal void Close() { if (!this.isClosed) { this.isClosed = true; this.localRunspacePool.Close(); this.localRunspacePool.StateChanged -= new EventHandler<RunspacePoolStateChangedEventArgs>(this.HandleRunspacePoolStateChanged); this.localRunspacePool.ForwardEvent -= new EventHandler<PSEventArgs>(this.HandleRunspacePoolForwardEvent); this.localRunspacePool.Dispose(); this.localRunspacePool = null; if (this.rsToUseForSteppablePipeline != null) { this.rsToUseForSteppablePipeline.Close(); this.rsToUseForSteppablePipeline.Dispose(); this.rsToUseForSteppablePipeline = null; } this.Closed.SafeInvoke<EventArgs>(this, EventArgs.Empty); } }
/// <summary> /// Construct a remote runspace based on the connection information /// and the specified host /// </summary> /// <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="connectionInfo">connection information which identifies /// the remote computer</param> /// <param name="host">host on the client</param> /// <param name="applicationArguments"> /// <param name="name">Friendly name for remote runspace session.</param> /// <param name="id">Id for remote runspace.</param> /// Application arguments the server can see in <see cref="System.Management.Automation.Remoting.PSSenderInfo.ApplicationArguments"/> /// </param> internal RemoteRunspace(TypeTable typeTable, RunspaceConnectionInfo connectionInfo, PSHost host, PSPrimitiveDictionary applicationArguments, string name = null, int id = -1) { PSEtwLog.SetActivityIdForCurrentThread(this.InstanceId); PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceConstructor, PSOpcode.Constructor, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, InstanceId.ToString()); _connectionInfo = connectionInfo.InternalCopy(); OriginalConnectionInfo = connectionInfo.InternalCopy(); RunspacePool = new RunspacePool(1, 1, typeTable, host, applicationArguments, connectionInfo, name); this.PSSessionId = id; SetEventHandlers(); }
// ---------- METHODS ---------- /// <summary> /// Disposes of system resources opened by the script. /// </summary> public virtual void Dispose() { // Dispose of the Script's RunspacePool. if (RunspacePool != null) { RunspacePool.Dispose(); } RunspacePool = null; }
public virtual Collection<PowerShell> CreateDisconnectedPowerShells(RunspacePool runspacePool) { throw PSTraceSource.NewInvalidOperationException(resBaseName, "RunspaceDisconnectConnectNotSupported", new object[0]); }
/// <summary> /// Creates a disconnected session for each disconnected PowerShell object in /// PSInvokeExpressionSyncJob. /// </summary> /// <param name="job"></param> /// <returns></returns> private List<PSSession> GetDisconnectedSessions(PSInvokeExpressionSyncJob job) { List<PSSession> discSessions = new List<PSSession>(); Collection<System.Management.Automation.PowerShell> powershells = job.GetPowerShells(); foreach (System.Management.Automation.PowerShell ps in powershells) { // Get the command information from the PowerShell object. string commandText = (ps.Commands != null && ps.Commands.Commands.Count > 0) ? ps.Commands.Commands[0].CommandText : string.Empty; ConnectCommandInfo cmdInfo = new ConnectCommandInfo(ps.InstanceId, commandText); // Get the old RunspacePool object that the command was initially run on. RunspacePool oldRunspacePool = null; if (ps.RunspacePool != null) { oldRunspacePool = ps.RunspacePool; } else { object rsConnection = ps.GetRunspaceConnection(); RunspacePool rsPool = rsConnection as RunspacePool; if (rsPool != null) { oldRunspacePool = rsPool; } else { RemoteRunspace remoteRs = rsConnection as RemoteRunspace; if (remoteRs != null) { oldRunspacePool = remoteRs.RunspacePool; } } } // Create a new disconnected PSSession object and return to the user. // The user can use this object to connect to the command on the server // and retrieve data. if (oldRunspacePool != null) { if (oldRunspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Disconnected) { // InvokeAndDisconnect starts the command and immediately disconnects the command, // but we need to disconnect the associated runspace/pool here. if (InvokeAndDisconnect && oldRunspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opened) { oldRunspacePool.Disconnect(); } else { // Skip runspace pools that have not been disconnected. continue; } } // Auto-generate a session name if one was not provided. string sessionName = oldRunspacePool.RemoteRunspacePoolInternal.Name; if (string.IsNullOrEmpty(sessionName)) { int id; sessionName = PSSession.GenerateRunspaceName(out id); } RunspacePool runspacePool = new RunspacePool( true, oldRunspacePool.RemoteRunspacePoolInternal.InstanceId, sessionName, new ConnectCommandInfo[1] { cmdInfo }, oldRunspacePool.RemoteRunspacePoolInternal.ConnectionInfo, this.Host, this.Context.TypeTable); runspacePool.RemoteRunspacePoolInternal.IsRemoteDebugStop = oldRunspacePool.RemoteRunspacePoolInternal.IsRemoteDebugStop; RemoteRunspace remoteRunspace = new RemoteRunspace(runspacePool); discSessions.Add(new PSSession(remoteRunspace)); } } return discSessions; }
protected override void Dispose(bool disposing) { Stop(); RunspacePool.Close(); RunspacePool.Dispose(); RunspacePool = null; base.Dispose(disposing); }
internal RestService(string serviceName, List<string> urls, List<RestCommand> commands, IEnumerable<string> modules) : base(serviceName, typeof(DynamicPowershell).Assembly) { // we have to give it at least one assembly, even if there isn't any services in it. // so I'm giving it a really small assembly _serviceName = serviceName; _activeCommands = commands; _listenOnUrls = urls; ReverseLookup.Clear(); var ss = InitialSessionState.CreateDefault(); ss.ImportPSModule(modules.ToArray()); RunspacePool = RunspaceFactory.CreateRunspacePool(ss); RunspacePool.Open(); }
internal RemoteRunspace(TypeTable typeTable, RunspaceConnectionInfo connectionInfo, PSHost host, PSPrimitiveDictionary applicationArguments, string name = null, int id = -1) { 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; PSEtwLog.SetActivityIdForCurrentThread(base.InstanceId); this._applicationArguments = applicationArguments; PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceConstructor, PSOpcode.Constructor, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, new object[] { base.InstanceId.ToString() }); if (connectionInfo is WSManConnectionInfo) { this._connectionInfo = ((WSManConnectionInfo) connectionInfo).Copy(); this._originalConnectionInfo = ((WSManConnectionInfo) connectionInfo).Copy(); } else if (connectionInfo is NewProcessConnectionInfo) { this._connectionInfo = ((NewProcessConnectionInfo) connectionInfo).Copy(); this._originalConnectionInfo = ((NewProcessConnectionInfo) connectionInfo).Copy(); } this._runspacePool = new System.Management.Automation.Runspaces.RunspacePool(1, 1, typeTable, host, applicationArguments, connectionInfo, name); this.Id = id; this.SetEventHandlers(); }
/// <summary> /// Constructs a RemoteRunspace object based on the passed in RunspacePool object, /// with a starting state of Disconnected. /// </summary> /// <param name="runspacePool"></param> internal RemoteRunspace(RunspacePool runspacePool) { // The RemoteRunspace object can only be constructed this way with a RunspacePool that // is in the disconnected state. if ((runspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Disconnected) || !(runspacePool.ConnectionInfo is WSManConnectionInfo)) { throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.InvalidRunspacePool); } RunspacePool = runspacePool; // The remote runspace pool object can only have the value one set for min/max pools. // This sets the runspace pool object min/max pool values to one. The PSRP/WSMan stack // will fail during connection if the min/max pool values do not match. RunspacePool.RemoteRunspacePoolInternal.SetMinRunspaces(1); RunspacePool.RemoteRunspacePoolInternal.SetMaxRunspaces(1); _connectionInfo = runspacePool.ConnectionInfo.InternalCopy(); // Update runspace DisconnectedOn and ExpiresOn property from WSManConnectionInfo UpdateDisconnectExpiresOn(); // Initial state must be Disconnected. SetRunspaceState(RunspaceState.Disconnected, null); // Normal Availability for a disconnected runspace is "None", which means it can be connected. // However, we can also have disconnected runspace objects that are *not* available for // connection and in this case the Availability is set to "Busy". _runspaceAvailability = RunspacePool.RemoteRunspacePoolInternal.AvailableForConnection ? Runspaces.RunspaceAvailability.None : Runspaces.RunspaceAvailability.Busy; SetEventHandlers(); PSEtwLog.SetActivityIdForCurrentThread(this.InstanceId); PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceConstructor, PSOpcode.Constructor, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, this.InstanceId.ToString()); }
/// <summary> /// Runs a PowerShell command/script asynchronously. /// </summary> /// <param name="commandText">The text of the command to run.</param> /// <param name="pool">An open PowerShell Runspace pool this script will use to invoke its pipeline.</param> /// <param name="callback">The callback function used to process the results of the asynchronous run.</param> /// <param name="log">[Optional] The event log to log execptions to. May be null for no logging.</param> /// <param name="input">[Optional] A collection of strings representing command-line input sent to the script during execution.</param> /// <param name="stateValues">[Optional] A collection of named state values that should be passed through the invocation to the callback function.</param> /// <param name="parameterList">An array of key/value objects defining additional parameters to supply to the PowerShell script.</param> /// <returns>An WaitHandle object that can be used to determine when the scrip has completed execution. Null if an error occurred while processing the command / script.</returns> public static WaitHandle RunAsynchronously(string commandText, ref RunspacePool pool, ProcessResults callback, EventLog.EventLog log = null, PSDataCollection<string> input = null, Dictionary<String, Object> stateValues = null, params KeyValuePair<String, Object>[] parameterList) { try { // Create the script object. PS script = PS.Create(); // Use the runspace pool supplied or create a new one if not supplied. if (pool == null) { pool = RunspaceFactory.CreateRunspacePool(DEFAULT_MIN_RUNSPACES_IN_POOL, DEFAULT_MAX_RUNSPACES_IN_POOL, CreateRunspaceConnectionInfo()); } // Verify that the pool is open, otherwise open it. if (pool.RunspacePoolStateInfo.State != RunspacePoolState.Opened) { pool.Open(); } // Add the runspace pool to the script object. script.RunspacePool = pool; // Create the PowerShell command object. Command command = new Command(commandText, true); // Add parameters to the command. if (parameterList != null) { foreach (KeyValuePair<string, object> param in parameterList) { command.Parameters.Add(new CommandParameter(param.Key, param.Value)); } } // Add the command to the script object. script.Commands.AddCommand(command); // Initialize the script input object if nothing was supplied. if (input == null) { input = new PSDataCollection<string>(); } // Initialize the state object to maintain data across the invocation. PowerShellScriptState state = new PowerShellScriptState(script); // Add the callback function used to process the results of the script invocation. state.StateVariables.Add(PROCESS_RESULTS_CALLBACK, callback); // Add any state values passed into the method. if (stateValues != null) { foreach (string key in stateValues.Keys) { state.StateVariables.Add(key, stateValues[key]); } } // Invoke the command asyncronously. return (script.BeginInvoke(input, new PSInvocationSettings(), ProcessAsynchronousResults, state)).AsyncWaitHandle; } catch (Exception e) { LogException(e, log); return null; } }
public DynamicPowershell(RunspacePool runspacePool) { _runspacePool = new AccessPrivateWrapper(runspacePool); if(_runspacePool.RunspacePoolStateInfo.State == RunspacePoolState.BeforeOpen) { _runspacePool.Open(); } _runspaceIsOwned = false; }
private List<PSSession> GetDisconnectedSessions(PSInvokeExpressionSyncJob job) { List<PSSession> list = new List<PSSession>(); foreach (PowerShell shell in job.GetPowerShells()) { string cmdStr = ((shell.Commands != null) && (shell.Commands.Commands.Count > 0)) ? shell.Commands.Commands[0].CommandText : string.Empty; ConnectCommandInfo info = new ConnectCommandInfo(shell.InstanceId, cmdStr); RunspacePool runspacePool = null; if (shell.RunspacePool != null) { runspacePool = shell.RunspacePool; } else { object runspaceConnection = shell.GetRunspaceConnection(); RunspacePool pool2 = runspaceConnection as RunspacePool; if (pool2 != null) { runspacePool = pool2; } else { RemoteRunspace runspace = runspaceConnection as RemoteRunspace; if (runspace != null) { runspacePool = runspace.RunspacePool; } } } if (runspacePool != null) { if (runspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Disconnected) { if (!base.InvokeAndDisconnect || (runspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Opened)) { continue; } runspacePool.Disconnect(); } string name = runspacePool.RemoteRunspacePoolInternal.Name; if (string.IsNullOrEmpty(name)) { int num; name = PSSession.GenerateRunspaceName(out num); } RunspacePool pool3 = new RunspacePool(true, runspacePool.RemoteRunspacePoolInternal.InstanceId, name, new ConnectCommandInfo[] { info }, runspacePool.RemoteRunspacePoolInternal.ConnectionInfo, base.Host, base.Context.TypeTable); RemoteRunspace remoteRunspace = new RemoteRunspace(pool3); list.Add(new PSSession(remoteRunspace)); } } return list; }
public override Collection<PowerShell> CreateDisconnectedPowerShells(RunspacePool runspacePool) { Collection<PowerShell> collection = new Collection<PowerShell>(); if (this.ConnectCommands == null) { throw new InvalidRunspacePoolStateException(StringUtil.Format(RunspacePoolStrings.CannotReconstructCommands, this.Name)); } foreach (ConnectCommandInfo info in this.ConnectCommands) { collection.Add(new PowerShell(info, runspacePool)); } return collection; }
public RunspacePool GetRunspacePool() { if (null == _rsPool) { lock (this) { if (null == _rsPool) { if (PsModulesToImport.Length > 0) { InitialSessionState initial = InitialSessionState.CreateDefault(); initial.ImportPSModule(PsModulesToImport); _rsPool = RunspaceFactory.CreateRunspacePool(initial); } else { _rsPool = RunspaceFactory.CreateRunspacePool(); } _rsPool.Open(); } } } return _rsPool; }
internal static RunspacePool[] GetRemoteRunspacePools(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable) { WSManConnectionInfo wsmanConnectionInfo = connectionInfo as WSManConnectionInfo; if (wsmanConnectionInfo == null) { throw new NotSupportedException(); } List<RunspacePool> list = new List<RunspacePool>(); foreach (PSObject obj2 in RemoteRunspacePoolEnumeration.GetRemotePools(wsmanConnectionInfo)) { WSManConnectionInfo info2 = wsmanConnectionInfo.Copy(); PSPropertyInfo info3 = obj2.Properties["ShellId"]; PSPropertyInfo info4 = obj2.Properties["State"]; PSPropertyInfo info5 = obj2.Properties["Name"]; PSPropertyInfo info6 = obj2.Properties["ResourceUri"]; if (((info3 != null) && (info4 != null)) && ((info5 != null) && (info6 != null))) { string name = info5.Value.ToString(); string str2 = info6.Value.ToString(); bool isDisconnected = info4.Value.ToString().Equals("Disconnected", StringComparison.OrdinalIgnoreCase); Guid shellId = Guid.Parse(info3.Value.ToString()); if (str2.StartsWith("http://schemas.microsoft.com/powershell/", StringComparison.OrdinalIgnoreCase)) { Collection<PSObject> remoteCommands; UpdateWSManConnectionInfo(info2, obj2); info2.EnableNetworkAccess = true; List<ConnectCommandInfo> list2 = new List<ConnectCommandInfo>(); try { remoteCommands = RemoteRunspacePoolEnumeration.GetRemoteCommands(shellId, info2); } catch (CmdletInvocationException exception) { if ((exception.InnerException == null) || !(exception.InnerException is InvalidOperationException)) { throw; } continue; } foreach (PSObject obj3 in remoteCommands) { PSPropertyInfo info7 = obj3.Properties["CommandId"]; PSPropertyInfo info8 = obj3.Properties["CommandLine"]; if (info7 != null) { string cmdStr = (info8 != null) ? info8.Value.ToString() : string.Empty; Guid cmdId = Guid.Parse(info7.Value.ToString()); list2.Add(new ConnectCommandInfo(cmdId, cmdStr)); } } RunspacePool item = new RunspacePool(isDisconnected, shellId, name, list2.ToArray(), info2, host, typeTable); list.Add(item); } } } return list.ToArray(); }
public void Release() { if (null != _rsPool) { lock (this) { if (null != _rsPool) { _rsPool.Close(); _rsPool.Dispose(); _rsPool = null; } } } }
public MsPowerShellHost(RunspacePool rsPool) { _ps = PowerShell.Create(); _ps.RunspacePool = rsPool; Init(); }
internal RestService(string serviceName, List<string> urls, List<RestCommand> commands, IEnumerable<string> modules) : base(serviceName, GetActiveAssemblies().ToArray()) { _serviceName = serviceName; _activeCommands = commands; _listenOnUrls = urls; ReverseLookup.Clear(); var ss = InitialSessionState.CreateDefault(); ss.ImportPSModule(modules.ToArray()); RunspacePool = RunspaceFactory.CreateRunspacePool(ss); RunspacePool.Open(); }