/// <summary> /// Initialize the runspace pool. /// </summary> /// <param name="minRunspaces"></param> /// <param name="maxRunspaces"></param> public void InitializeRunspaces(int minRunspaces, int maxRunspaces, string[] modulesToLoad) { // create the default session state. // session state can be used to set things like execution policy, language constraints, etc. // optionally load any modules (by name) that were supplied. var defaultSessionState = InitialSessionState.CreateDefault(); defaultSessionState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted; foreach (var moduleName in modulesToLoad) { defaultSessionState.ImportPSModule(moduleName); } // use the runspace factory to create a pool of runspaces // with a minimum and maximum number of runspaces to maintain. RsPool = RunspaceFactory.CreateRunspacePool(defaultSessionState); RsPool.SetMinRunspaces(minRunspaces); RsPool.SetMaxRunspaces(maxRunspaces); // set the pool options for thread use. // we can throw away or re-use the threads depending on the usage scenario. RsPool.ThreadOptions = PSThreadOptions.UseNewThread; // open the pool. // this will start by initializing the minimum number of runspaces. RsPool.Open(); }
/// <summary> /// Initialize the runspace pool. /// </summary> /// <param name="runspace">Contains runspace config parameters necessary for the script</param> public void InitializeRunspaces(ScriptRunspace runspace) { // create the default session state. // session state can be used to set things like execution policy, language constraints, etc. var defaultSessionState = InitialSessionState.CreateDefault(); if (!String.IsNullOrEmpty(runspace.ExecutionPolicy)) { defaultSessionState.ExecutionPolicy = runspace.ExecutionPolicy.ToEnum <Microsoft.PowerShell.ExecutionPolicy>(); } // optionally load any modules (by name) that were supplied. foreach (var moduleName in runspace.Modules) { defaultSessionState.ImportPSModule(moduleName); } // use the runspace factory to create a pool of runspaces with a minimum and maximum number of runspaces to maintain. RsPool = RunspaceFactory.CreateRunspacePool(defaultSessionState); RsPool.SetMinRunspaces(runspace.Min); RsPool.SetMaxRunspaces(runspace.Max); // set the pool options for thread use. // we can throw away or re-use the threads depending on the usage scenario. RsPool.ThreadOptions = PSThreadOptions.UseNewThread; // open the pool. this will start by initializing the minimum number of runspaces. RsPool.Open(); }
public InvokeParallelTests() { var iss = InitialSessionState.Create(); iss.LanguageMode = PSLanguageMode.FullLanguage; iss.Commands.Add(new [] { new SessionStateCmdletEntry("Write-Error", typeof(WriteErrorCommand), null), new SessionStateCmdletEntry("Write-Verbose", typeof(WriteVerboseCommand), null), new SessionStateCmdletEntry("Write-Debug", typeof(WriteDebugCommand), null), new SessionStateCmdletEntry("Write-Progress", typeof(WriteProgressCommand), null), new SessionStateCmdletEntry("Write-Warning", typeof(WriteWarningCommand), null), new SessionStateCmdletEntry("Write-Information", typeof(WriteInformationCommand), null), new SessionStateCmdletEntry("Invoke-Parallel", typeof(InvokeParallelCommand), null), }); iss.Providers.Add(new SessionStateProviderEntry("Function", typeof(FunctionProvider), null)); iss.Providers.Add(new SessionStateProviderEntry("Variable", typeof(VariableProvider), null)); iss.Variables.Add(new [] { new SessionStateVariableEntry("ErrorActionPreference", ActionPreference.Continue, "Dictates the action taken when an error message is delivered"), }); m_runspacePool = RunspaceFactory.CreateRunspacePool(iss); m_runspacePool.SetMaxRunspaces(10); m_runspacePool.Open(); }
// In this function the activity action is performed private void PerformWork(ActivityActionData data) { bool failed = false; Exception exception = null; try { // setting up the streams data.command.Streams.Debug = data.streams.DebugStream; data.command.Streams.Error = data.streams.ErrorStream; data.command.Streams.Progress = data.streams.ProgressStream; data.command.Streams.Verbose = data.streams.VerboseStream; data.command.Streams.Warning = data.streams.WarningStream; // Custom WinRM Workflow Endpoint details // run CustomWorkflowEndpointSetup.ps1 in Powershell console as administrator, if you have not done. // WSManConnectionInfo connectionInfo = new WSManConnectionInfo(); connectionInfo.ShellUri = "http://schemas.microsoft.com/powershell/CustomeWorkflowEndpoint"; // Create runspace pool on custom workflow endpoint where command will be invoked using (RunspacePool r = RunspaceFactory.CreateRunspacePool(1, 1, connectionInfo)) { try { r.Open(); data.command.RunspacePool = r; // now executing the powershell command. data.command.Invoke(data.streams.InputStream, data.streams.OutputStream, new PSInvocationSettings()); } finally { r.Close(); r.Dispose(); } } } catch (Exception e) { // since work is getting performed on background thread so there should not be any exception. failed = true; exception = e; } // Now since activity action has already been performed so now we need to resume the execution of the // workflow. This will be done by PSWorkflowJob job = _runtime.JobManager.GetJob(data.jobInstanceId); // Now resuming the job if (failed) { job.ResumeBookmark(data.bookmark, this.SupportDisconnectedPSStreams, data.streams, exception); } else { job.ResumeBookmark(data.bookmark, this.SupportDisconnectedPSStreams, data.streams); } }
public static ExamplePowerShellService Create(int maxRunspaces) { RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(minRunspaces: 1, maxRunspaces); runspacePool.Open(); return(new ExamplePowerShellService(runspacePool)); }
/// <summary> /// Create a fresh command info cache instance. /// </summary> public CommandInfoCache(Helper pssaHelperInstance) { _commandInfoCache = new ConcurrentDictionary <CommandLookupKey, Lazy <CommandInfo> >(); _helperInstance = pssaHelperInstance; _runspacePool = RunspaceFactory.CreateRunspacePool(1, 10); _runspacePool.Open(); }
/// <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(); }
public InvokeParallelTests() { _iss = CreateInitialSessionState(); m_runspacePool = RunspaceFactory.CreateRunspacePool(_iss); m_runspacePool.SetMaxRunspaces(10); m_runspacePool.Open(); }
/// <summary> /// Runs many commands with the help of a RunspacePool. /// </summary> /// <param name="args">This parameter is unused.</param> private static void Main(string[] args) { // Creating and opening runspace pool. Use a minimum of 1 runspace and a maximum of // 5 runspaces can be opened at the same time. RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(1, 5); runspacePool.Open(); using (runspacePool) { // Define the commands to be run. List <PowerShell> powerShellCommands = new List <PowerShell>(); // The command results. List <IAsyncResult> powerShellCommandResults = new List <IAsyncResult>(); // The maximum number of runspaces that can be opened at one time is // 5, but we can queue up many more commands that will use the // runspace pool. for (int i = 0; i < 100; i++) { // Using a PowerShell object, run the commands. PowerShell powershell = PowerShell.Create(); // Instead of setting the Runspace property of powershell, // the RunspacePool property is used. That is the only difference // between running commands with a runspace and running commands // with a runspace pool. powershell.RunspacePool = runspacePool; // The script to be run outputs a sequence number and the number of available runspaces // in the pool. string script = String.Format( "write-output ' Command: {0}, Available Runspaces: {1}'", i, runspacePool.GetAvailableRunspaces()); // The three lines below look the same running with a runspace or // with a runspace pool. powershell.AddScript(script); powerShellCommands.Add(powershell); powerShellCommandResults.Add(powershell.BeginInvoke()); } // Collect the results. for (int i = 0; i < 100; i++) { // EndInvoke will wait for each command to finish, so we will be getting the commands // in the same 0 to 99 order that they have been invoked withy BeginInvoke. PSDataCollection <PSObject> results = powerShellCommands[i].EndInvoke(powerShellCommandResults[i]); // Print all the results. One PSObject with a plain string is the expected result. PowerShell02.PrintCollection(results); } } }
/// <summary> /// Create a new runspace pool around a PSScriptAnalyzer module for asynchronous script analysis tasks. /// This looks for the latest version of PSScriptAnalyzer on the path and loads that. /// </summary> /// <returns>A runspace pool with PSScriptAnalyzer loaded for running script analysis tasks.</returns> private static RunspacePool CreatePssaRunspacePool(out PSModuleInfo pssaModuleInfo) { using (var ps = System.Management.Automation.PowerShell.Create()) { // Run `Get-Module -ListAvailable -Name "PSScriptAnalyzer"` ps.AddCommand("Get-Module") .AddParameter("ListAvailable") .AddParameter("Name", PSSA_MODULE_NAME); try { using (PSModulePathPreserver.Take()) { // Get the latest version of PSScriptAnalyzer we can find pssaModuleInfo = ps.Invoke <PSModuleInfo>()? .OrderByDescending(moduleInfo => moduleInfo.Version) .FirstOrDefault(); } } catch (Exception e) { throw new FileNotFoundException("Unable to find PSScriptAnalyzer module on the module path", e); } if (pssaModuleInfo == null) { throw new FileNotFoundException("Unable to find PSScriptAnalyzer module on the module path"); } // Now that we know where the PSScriptAnalyzer we want to use is, // create a base session state with PSScriptAnalyzer loaded #if DEBUG InitialSessionState sessionState = Environment.GetEnvironmentVariable("PSES_TEST_USE_CREATE_DEFAULT") == "1" ? InitialSessionState.CreateDefault() : InitialSessionState.CreateDefault2(); #else InitialSessionState sessionState = InitialSessionState.CreateDefault2(); #endif sessionState.ImportPSModule(new [] { pssaModuleInfo.ModuleBase }); RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(sessionState); runspacePool.SetMaxRunspaces(1); runspacePool.ThreadOptions = PSThreadOptions.ReuseThread; // Open the runspace pool here so we can deterministically handle the PSModulePath change issue using (PSModulePathPreserver.Take()) { runspacePool.Open(); } return(runspacePool); } }
/// <summary> /// Runs commmands or script in a new /// PowerShell runspace pool. /// </summary> /// <param name="script"></param> /// <param name="parameters"></param> /// <returns>PSResults object: A collection of PSObjects that were returned from the script or command, and /// the error and information streams. /// </returns> public static PSResults RunPowerShellScript(string script, Dictionary <String, Object> parameters) { Collection <PSObject> objects; using (RunspacePool rsp = RunspaceFactory.CreateRunspacePool()) { rsp.Open(); PowerShell instance = null; try { instance = PowerShell.Create(); instance.RunspacePool = rsp; instance.AddScript(script); if (parameters != null) { foreach (var p in parameters) { instance.AddParameter(p.Key, p.Value); } } objects = instance.Invoke(); var res = new PSResults(); res.ReturnedObjects = objects ?? new Collection <PSObject>(); if (instance.Streams.Error.Count > 0) { res.Errors = new ErrorRecord[instance.Streams.Error.Count]; instance.Streams.Error.CopyTo(res.Errors, 0); } else { res.Errors = new ErrorRecord[0]; } if (instance.Streams.Information.Count > 0) { res.Information = new InformationRecord[instance.Streams.Information.Count]; instance.Streams.Information.CopyTo(res.Information, 0); } else { res.Information = new InformationRecord[0]; } return(res); } finally { instance?.Dispose(); } } }
static PSControllerExtensions() { int maxWorkerThreads, maxIOThreads; ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxIOThreads); _runspacePool = RunspaceFactory.CreateRunspacePool(1, maxWorkerThreads); _runspacePool.Open(); _escapedNewLine = Uri.EscapeDataString(Environment.NewLine).ToLower(); }
/// <summary> /// Create a new runspace pool around a PSScriptAnalyzer module for asynchronous script analysis tasks. /// This looks for the latest version of PSScriptAnalyzer on the path and loads that. /// </summary> /// <returns>A runspace pool with PSScriptAnalyzer loaded for running script analysis tasks.</returns> private static RunspacePool CreatePssaRunspacePool(out PSModuleInfo pssaModuleInfo) { using (var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.NewRunspace)) { // Run `Get-Module -ListAvailable -Name "PSScriptAnalyzer"` ps.AddCommand("Get-Module") .AddParameter("ListAvailable") .AddParameter("Name", PSSA_MODULE_NAME); try { using (PSModulePathPreserver.Take()) { // Get the latest version of PSScriptAnalyzer we can find pssaModuleInfo = ps.Invoke <PSModuleInfo>()? .OrderByDescending(moduleInfo => moduleInfo.Version) .FirstOrDefault(); } } catch (Exception e) { throw new FileNotFoundException("Unable to find PSScriptAnalyzer module on the module path", e); } if (pssaModuleInfo == null) { throw new FileNotFoundException("Unable to find PSScriptAnalyzer module on the module path"); } // Now that we know where the PSScriptAnalyzer we want to use is, create a base // session state with PSScriptAnalyzer loaded // // We intentionally use `CreateDefault2()` as it loads `Microsoft.PowerShell.Core` // only, which is a more minimal and therefore safer state. InitialSessionState sessionState = InitialSessionState.CreateDefault2(); sessionState.ImportPSModule(new [] { pssaModuleInfo.ModuleBase }); RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(sessionState); runspacePool.SetMaxRunspaces(1); runspacePool.ThreadOptions = PSThreadOptions.ReuseThread; // Open the runspace pool here so we can deterministically handle the PSModulePath change issue using (PSModulePathPreserver.Take()) { runspacePool.Open(); } return(runspacePool); } }
public PowershellEngine() { var iss = InitialSessionState.CreateDefault2(); _runspace = RunspaceFactory.CreateRunspacePool(iss); _runspace.Open(); using (var ps = CreateShell()) { ps.AddScript("import-module Hyper-V -RequiredVersion 1.1"); ps.Invoke(); } }
protected override void BeginProcessing() { base.BeginProcessing(); sessionState = InitialSessionState.CreateDefault(); WriteVerbose("Created initial session state.."); runspacePool = RunspaceFactory.CreateRunspacePool(1, maxThreads, sessionState, this.Host); runspacePool.Open(); WriteVerbose("Runspace pool created.."); scriptBlock = InvokeCommand.NewScriptBlock(string.Format("param($_)\r\n{0}", scriptBlock.ToString())); WriteVerbose("Modified scriptblock.."); }
protected override void BeginProcessing() { // Build the results ArrayList final = new ArrayList(); Hashtable rsColl = new Hashtable(); int c = 0; using (RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(1, MaxThreads)) { try { runspacePool.Open(); foreach (object obj in InputObject) { PowerShell powerShell = PowerShell.Create(); powerShell .AddScript(ScriptBlock) .AddArgument(obj); try { powerShell.AddParameters(ArgumentList); } catch (Exception) { } IAsyncResult psAsyncResult = powerShell.BeginInvoke(); rsColl.Add("psResult", psAsyncResult); rsColl.Add("psPowerShell", powerShell); //PSDataCollection<PSObject> psOutput = powerShell.EndInvoke(psAsyncResult); //final.Add(psOutput); //powerShell.Dispose(); } // End foreach //runspacePool.Close(); //runspacePool.Dispose(); } catch (Exception) { throw; } } // End using // Output to console WriteObject(final, true); }
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(); }
private static Collection <PSObject> runPowershellCommands(PSCommand commandsToRun) { if (pool.RunspacePoolStateInfo.State != RunspacePoolState.Opened) { pool.Close(); pool = RunspaceFactory.CreateRunspacePool(1, 5, connection); pool.Open(); } PowerShell powershell = PowerShell.Create(); powershell.Commands = commandsToRun; powershell.RunspacePool = pool; Collection <PSObject> results = powershell.Invoke(); powershell.Dispose(); return(results); }
public (string, string) InMemoryPfxRunspacePool() { // IApplicationEnvironment for ASP.NET Core string asmPath = System.Reflection.Assembly.GetExecutingAssembly().Location; string rootFolder = System.IO.Path.GetDirectoryName(asmPath); var timer = Stopwatch.StartNew(); var defaultSessionState = InitialSessionState.CreateDefault(); defaultSessionState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted; defaultSessionState.ThrowOnRunspaceOpenError = true; defaultSessionState.ImportPSModule(new string[] { "ExchangeOnlineManagement" }); defaultSessionState.Variables.Add(new SessionStateVariableEntry("exoAppId", AppId, "no description")); defaultSessionState.Variables.Add(new SessionStateVariableEntry("exoOrganization", Organization, "no description")); defaultSessionState.Variables.Add(new SessionStateVariableEntry("exoCertificate", Certificate, "no description")); bool result = defaultSessionState.StartupScripts.Add(System.IO.Path.Combine(rootFolder, "ConnectExO.ps1")); using (RunspacePool RsPool = RunspaceFactory.CreateRunspacePool(defaultSessionState)) { RsPool.SetMinRunspaces(1); RsPool.SetMaxRunspaces(3); RsPool.ThreadOptions = PSThreadOptions.UseNewThread; RsPool.Open(); var ts1 = timer.Elapsed; using (var ps = PowerShell.Create()) { ps.RunspacePool = RsPool; // ps.Commands.Clear(); ps.Commands.AddCommand("Get-EXOMailBox") .AddParameter("ResultSize", "unlimited"); // var pipelineObjects = await ps.InvokeAsync().ConfigureAwait(false); List <PSObject> results = ps.Invoke().ToList(); var ts2 = timer.Elapsed; return(FlattenErrors(ps), ResultsToSimpleString(results)); } } }
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(); }
public void Start(int port = 3000, int minRunspaces = 1, int maxRunspaces = 1) { StopServer = false; PowerShellPool = RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces); PowerShellPool.Open(); Listener = InitListener(port); Thread listenerThread = new Thread(async() => { await ListenerLoop(); }); listenerThread.Start(); // Loop until worker thread activates. while (!listenerThread.IsAlive) { ; } Log("App listening on Port: " + port + "!"); }
// ---------- 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(); } }
protected RunspacePool GetRunspacePool(string server, string userName, string password) { if (RunspacePools.ContainsKey(server)) { return(RunspacePools[server]); } else { System.Security.SecureString pwd = new System.Security.SecureString(); foreach (char c in password.ToCharArray()) { pwd.AppendChar(c); } var remoteComputer = new Uri(String.Format("{0}://{1}:5985/wsman", "http", server)); var connection = new WSManConnectionInfo(remoteComputer, "", new PSCredential(userName, pwd)); connection.AuthenticationMechanism = AuthenticationMechanism.Credssp; RunspacePool pool = RunspaceFactory.CreateRunspacePool(1, 5, connection); pool.ApartmentState = System.Threading.ApartmentState.MTA; pool.Open(); RunspacePools[server] = pool; return(pool); } }
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); }
/// <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> static public 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); } }
/// <summary> /// This sample shows how to construct a remote RunspacePool and run /// multiple commands concurrently using the runspaces of the pool. /// </summary> /// <param name="args">Parameter is not used.</param> public static void Main(string[] args) { // Create a WSManConnectionInfo object using the default constructor to // connexct to the "localhost". The WSManConnectionInfo object can also // specify connections to remote computers. WSManConnectionInfo connectionInfo = new WSManConnectionInfo(); // Create a remote runspace pool that uses the WSManConnectionInfo object. // The minimum runspaces value of 1 and maximum runspaces value of 2 allows // Windows PowerShell to open a maximum of 2 runspaces at the same time so // that two commands can be run concurrently. using (RunspacePool remoteRunspacePool = RunspaceFactory.CreateRunspacePool(1, 2, connectionInfo)) { // Call the Open() method to open a runspace and establish the connection. remoteRunspacePool.Open(); // Call the Create() method to create a pipeline, call the AddCommand(string) // method to add the "get-process" command, and then call the BeginInvoke() // method to run the command asynchronously using the runspace pool. PowerShell gpsCommand = PowerShell.Create().AddCommand("get-process"); gpsCommand.RunspacePool = remoteRunspacePool; IAsyncResult gpsCommandAsyncResult = gpsCommand.BeginInvoke(); // The previous call does not block the current thread because it is // running asynchronously. Because the remote runspace pool can open two // runspaces, the second command can be run. PowerShell getServiceCommand = PowerShell.Create().AddCommand("get-service"); getServiceCommand.RunspacePool = remoteRunspacePool; IAsyncResult getServiceCommandAsyncResult = getServiceCommand.BeginInvoke(); // When you are ready to handle the output, wait for the command to complete // before extracting results. A call to the EndInvoke() method will block and return // the output. PSDataCollection <PSObject> gpsCommandOutput = gpsCommand.EndInvoke(gpsCommandAsyncResult); // Process the output as needed. if ((gpsCommandOutput != null) && (gpsCommandOutput.Count > 0)) { Console.WriteLine("The first output from running get-process command: "); Console.WriteLine( "Process Name: {0} Process Id: {1}", gpsCommandOutput[0].Properties["ProcessName"].Value, gpsCommandOutput[0].Properties["Id"].Value); Console.WriteLine(); } // Now process the output from second command. As discussed previously, wait // for the command to complete before extracting the results. PSDataCollection <PSObject> getServiceCommandOutput = getServiceCommand.EndInvoke( getServiceCommandAsyncResult); // Process the output of the second command as needed. if ((getServiceCommandOutput != null) && (getServiceCommandOutput.Count > 0)) { Console.WriteLine("The first output from running get-service command: "); Console.WriteLine( "Service Name: {0} Description: {1} State: {2}", getServiceCommandOutput[0].Properties["ServiceName"].Value, getServiceCommandOutput[0].Properties["DisplayName"].Value, getServiceCommandOutput[0].Properties["Status"].Value); } // Once done with running all the commands, close the remote runspace pool. // The Dispose() (called by using primitive) will call Close(), if it // is not already called. remoteRunspacePool.Close(); } }
public void Initialize() { m_posh_runspace_pool = RunspaceFactory.CreateRunspacePool(5, 25); m_posh_runspace_pool.ThreadOptions = PSThreadOptions.Default; m_posh_runspace_pool.Open(); }
/// <summary> /// GetExternalRecord: Get external rules in parallel using RunspacePool and run each rule in its own runspace. /// </summary> /// <param name="ast"></param> /// <param name="token"></param> /// <param name="rules"></param> /// <param name="command"></param> /// <param name="filePath"></param> /// <returns></returns> public IEnumerable <DiagnosticRecord> GetExternalRecord(Ast ast, Token[] token, ExternalRule[] rules, InvokeScriptAnalyzerCommand command, string filePath) { // Defines InitialSessionState. InitialSessionState state = InitialSessionState.CreateDefault2(); // Groups rules by module paths and imports them. Dictionary <string, List <ExternalRule> > modules = rules .GroupBy <ExternalRule, string>(item => item.GetFullModulePath()) .ToDictionary(item => item.Key, item => item.ToList()); state.ImportPSModule(modules.Keys.ToArray <string>()); // Creates and opens RunspacePool RunspacePool rsp = RunspaceFactory.CreateRunspacePool(state); rsp.SetMinRunspaces(1); rsp.SetMaxRunspaces(5); rsp.Open(); // Groups rules by AstType and Tokens. Dictionary <string, List <ExternalRule> > astRuleGroups = rules .Where <ExternalRule>(item => item.GetParameter().EndsWith("ast", StringComparison.OrdinalIgnoreCase)) .GroupBy <ExternalRule, string>(item => item.GetParameterType()) .ToDictionary(item => item.Key, item => item.ToList()); Dictionary <string, List <ExternalRule> > tokenRuleGroups = rules .Where <ExternalRule>(item => item.GetParameter().EndsWith("token", StringComparison.OrdinalIgnoreCase)) .GroupBy <ExternalRule, string>(item => item.GetParameterType()) .ToDictionary(item => item.Key, item => item.ToList()); using (rsp) { // Defines the commands to be run. List <System.Management.Automation.PowerShell> powerShellCommands = new List <System.Management.Automation.PowerShell>(); // Defines the command results. List <IAsyncResult> powerShellCommandResults = new List <IAsyncResult>(); #region Builds and invokes commands list foreach (KeyValuePair <string, List <ExternalRule> > tokenRuleGroup in tokenRuleGroups) { foreach (IExternalRule rule in tokenRuleGroup.Value) { System.Management.Automation.PowerShell posh = System.Management.Automation.PowerShell.Create(); posh.RunspacePool = rsp; // Adds command to run external analyzer rule, like // Measure-CurlyBracket -ScriptBlockAst $ScriptBlockAst // Adds module name (source name) to handle ducplicate function names in different modules. string ruleName = string.Format("{0}\\{1}", rule.GetSourceName(), rule.GetName()); posh.Commands.AddCommand(ruleName); posh.Commands.AddParameter(rule.GetParameter(), token); // Merges results because external analyzer rules may throw exceptions. posh.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); powerShellCommands.Add(posh); powerShellCommandResults.Add(posh.BeginInvoke()); } } foreach (KeyValuePair <string, List <ExternalRule> > astRuleGroup in astRuleGroups) { // Find all AstTypes that appeared in rule groups. IEnumerable <Ast> childAsts = ast.FindAll(new Func <Ast, bool>((testAst) => (astRuleGroup.Key.IndexOf(testAst.GetType().FullName, StringComparison.OrdinalIgnoreCase) != -1)), false); foreach (Ast childAst in childAsts) { foreach (IExternalRule rule in astRuleGroup.Value) { System.Management.Automation.PowerShell posh = System.Management.Automation.PowerShell.Create(); posh.RunspacePool = rsp; // Adds command to run external analyzer rule, like // Measure-CurlyBracket -ScriptBlockAst $ScriptBlockAst // Adds module name (source name) to handle ducplicate function names in different modules. string ruleName = string.Format("{0}\\{1}", rule.GetSourceName(), rule.GetName()); posh.Commands.AddCommand(ruleName); posh.Commands.AddParameter(rule.GetParameter(), childAst); // Merges results because external analyzer rules may throw exceptions. posh.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); powerShellCommands.Add(posh); powerShellCommandResults.Add(posh.BeginInvoke()); } } } #endregion #region Collects the results from commands. List <DiagnosticRecord> diagnostics = new List <DiagnosticRecord>(); try { for (int i = 0; i < powerShellCommands.Count; i++) { // EndInvoke will wait for each command to finish, so we will be getting the commands // in the same order that they have been invoked withy BeginInvoke. PSDataCollection <PSObject> psobjects = powerShellCommands[i].EndInvoke(powerShellCommandResults[i]); foreach (var psobject in psobjects) { DiagnosticSeverity severity; IScriptExtent extent; string message = string.Empty; string ruleName = string.Empty; if (psobject != null && psobject.ImmediateBaseObject != null) { // Because error stream is merged to output stream, // we need to handle the error records. if (psobject.ImmediateBaseObject is ErrorRecord) { ErrorRecord record = (ErrorRecord)psobject.ImmediateBaseObject; command.WriteError(record); continue; } // DiagnosticRecord may not be correctly returned from external rule. try { Enum.TryParse <DiagnosticSeverity>(psobject.Properties["Severity"].Value.ToString().ToUpper(), out severity); message = psobject.Properties["Message"].Value.ToString(); extent = (IScriptExtent)psobject.Properties["Extent"].Value; ruleName = psobject.Properties["RuleName"].Value.ToString(); } catch (Exception ex) { command.WriteError(new ErrorRecord(ex, ex.HResult.ToString("X"), ErrorCategory.NotSpecified, this)); continue; } if (!string.IsNullOrEmpty(message)) { diagnostics.Add(new DiagnosticRecord(message, extent, ruleName, severity, null)); } } } } } //Catch exception where customized defined rules have exceptins when doing invoke catch (Exception ex) { command.WriteError(new ErrorRecord(ex, ex.HResult.ToString("X"), ErrorCategory.NotSpecified, this)); } return(diagnostics); #endregion } }
public void Open() { _runspacePool.Open(); }
public static void OpenRunspace(PSCredential credentials) { connection = getConnection(credentials); pool = RunspaceFactory.CreateRunspacePool(1, 5, connection); pool.Open(); }