Beispiel #1
0
        /// <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();
        }
Beispiel #2
0
        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();
        }
        /// <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();
        }
Beispiel #4
0
        public static ExamplePowerShellService Create(int maxRunspaces)
        {
            RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(minRunspaces: 1, maxRunspaces);

            runspacePool.Open();
            return(new ExamplePowerShellService(runspacePool));
        }
Beispiel #5
0
        /// <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();
        }
Beispiel #6
0
 /// <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 an instance of the AnalysisService class.
        /// </summary>
        /// <param name="settingsPath">Path to a PSScriptAnalyzer settings file.</param>
        /// <param name="logger">An ILogger implementation used for writing log messages.</param>
        public AnalysisService(string settingsPath, ILogger logger)
        {
            this.logger = logger;

            try
            {
                this.SettingsPath = settingsPath;

                scriptAnalyzerModuleInfo = FindPSScriptAnalyzerModule(logger);
                var sessionState = InitialSessionState.CreateDefault2();
                sessionState.ImportPSModulesFromPath(scriptAnalyzerModuleInfo.ModuleBase);

                // runspacepool takes care of queuing commands for us so we do not
                // need to worry about executing concurrent commands
                this.analysisRunspacePool = RunspaceFactory.CreateRunspacePool(sessionState);

                // having more than one runspace doesn't block code formatting if one
                // runspace is occupied for diagnostics
                this.analysisRunspacePool.SetMaxRunspaces(NumRunspaces);
                this.analysisRunspacePool.ThreadOptions = PSThreadOptions.ReuseThread;
                this.analysisRunspacePool.Open();

                ActiveRules = IncludedRules.ToArray();
                EnumeratePSScriptAnalyzerRules();
            }
            catch (Exception e)
            {
                var sb = new StringBuilder();
                sb.AppendLine("PSScriptAnalyzer cannot be imported, AnalysisService will be disabled.");
                sb.AppendLine(e.Message);
                this.logger.Write(LogLevel.Warning, sb.ToString());
            }
        }
Beispiel #8
0
 public InvokeParallelTests()
 {
     _iss           = CreateInitialSessionState();
     m_runspacePool = RunspaceFactory.CreateRunspacePool(_iss);
     m_runspacePool.SetMaxRunspaces(10);
     m_runspacePool.Open();
 }
Beispiel #9
0
 private static void InitSharedPool()
 {
     if (_sharedRunspacePool == null)
     {
         _sharedRunspacePool = new OnDisposable <RunspacePool>(RunspaceFactory.CreateRunspacePool());
         _sharedRunspacePool.Value.Open();
     }
 }
Beispiel #10
0
        public static PowerShellJob MakePowerShellJob(Action <PowerShell> configure,
                                                      Action <dynamic> process, Action <Exception> errors = null)
        {
            var pShell = new PowerShellJob((runspacePool) =>
            {
                try
                {
                    using (var localRunspacePool = RunspaceFactory.CreateRunspacePool())
                    {
                        localRunspacePool.Open();
                        using (var engine = PowerShell.Create())
                        {
                            engine.RunspacePool = localRunspacePool;
                            engine.AddScript(@"");
                            //engine.AddScript(@"Import-Module RemoteDesktop");
                            //engine.Commands.AddCommand("Import-Module").AddArgument("ActiveDirectory");
                            var importResult = engine.BeginInvoke();
                            var result       = engine.EndInvoke(importResult);
                            configure(engine);

                            var invokeResult = engine.BeginInvoke();
                            var commandIter  = engine.EndInvoke(invokeResult);

                            if (engine.Streams.Error != null &&
                                engine.Streams.Error.Count > 0)
                            {
                                ErrorHelper.WriteErrorToEventLog(PowerShellJob.GetErrorMessage(engine.Streams.Error));
                                throw new Exception(PowerShellJob.GetErrorMessage(engine.Streams.Error));
                            }

                            foreach (dynamic psObject in commandIter)
                            {
                                if (process != null)
                                {
                                    process(psObject);
                                }
                            }
                        }
                    }

                    return(true);
                }
                catch (Exception ex)
                {
                    ErrorHelper.WriteErrorToEventLog(ex.Message);
                    if (errors != null)
                    {
                        errors(ex);
                    }
                }

                return(false);
            });

            pShell.ReOccuring = false;
            return(pShell);
        }
        /// <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);
                }
            }
        }
Beispiel #12
0
        /// <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();
        }
        public static (string, string) WSManConnectToExO(string admin, string pass)
        {
            using (var ps = PowerShell.Create())
            {
                var secureString = new SecureString();
                pass.ToCharArray().ToList().ForEach(p => secureString.AppendChar(p));
                var credential = new PSCredential(admin, secureString);

                var connectionInfo = new WSManConnectionInfo(
                    new Uri("https://outlook.office365.com/powershell-liveid/"),
                    "http://schemas.microsoft.com/powershell/Microsoft.Exchange",
                    credential);
                connectionInfo.AuthenticationMechanism           = AuthenticationMechanism.Basic;
                connectionInfo.MaximumConnectionRedirectionCount = 2;

                var pool = RunspaceFactory.CreateRunspacePool(1, 5, connectionInfo);
                pool.ThreadOptions = PSThreadOptions.UseNewThread;
                pool.Open();

                ps.RunspacePool = pool;

                ps.AddCommand("Get-Mailbox");
                ps.AddParameter("Identity", admin);

                ps.AddCommand("Select-Object");
                ps.AddParameter("ExpandProperty", "EmailAddresses");
                List <PSObject> results = ps.Invoke().ToList();

                string errors = "";
                if (ps.Streams.Error.Count > 0)
                {
                    errors = "!Errors! " + String.Join(" :: ", ps.StreamErrorsToErrorList());
                }

                if (!results.Any())
                {
                    errors += "Identity not found";
                }

                var addressesArray = results.Select(psObject => psObject.Properties["ProxyAddressString"].Value.ToString()).ToList();
                var aliasAddresses = (from address in addressesArray where address.StartsWith("smtp:", StringComparison.InvariantCulture) select address.Substring("smtp:".Length)).ToList();
                var addresses      = addressesArray.Where(a => !a.StartsWith("SMTP:")).ToList();

                StringBuilder stb = new StringBuilder();
                stb.AppendLine("Alias addresses: " + String.Join(",", aliasAddresses));
                stb.AppendLine("SMTP: " + String.Join(",", addresses));

                pool.Close();

                return(errors, stb.ToString());
            }
        }
Beispiel #16
0
        /// <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);
            }
        }
Beispiel #17
0
        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();
            }
        }
 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)
 {
     using (ServerRunspacePoolDriver.tracer.TraceConstructor((object)this))
     {
         this.serverCapability = serverCapability;
         ServerRemoteHost serverRemoteHost = new ServerRemoteHost(clientRunspacePoolId, Guid.Empty, hostInfo, (AbstractServerTransportManager)transportManager);
         this.remoteHost             = serverRemoteHost;
         this.configData             = configData;
         this.applicationPrivateData = applicationPrivateData;
         this.localRunspacePool      = RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces, initialSessionState, (PSHost)serverRemoteHost);
         PSThreadOptions psThreadOptions = configData.ShellThreadOptions.HasValue ? configData.ShellThreadOptions.Value : PSThreadOptions.UseCurrentThread;
         if (threadOptions == PSThreadOptions.Default || threadOptions == psThreadOptions)
         {
             this.localRunspacePool.ThreadOptions = psThreadOptions;
         }
         else
         {
             if (!isAdministrator)
             {
                 throw new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(PSRemotingErrorId.MustBeAdminToOverrideThreadOptions));
             }
             this.localRunspacePool.ThreadOptions = threadOptions;
         }
         ApartmentState apartmentState1 = configData.ShellThreadApartmentState.HasValue ? configData.ShellThreadApartmentState.Value : ApartmentState.Unknown;
         this.localRunspacePool.ApartmentState = apartmentState == ApartmentState.Unknown || apartmentState == apartmentState1 ? apartmentState1 : 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);
     }
 }
        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..");
        }
Beispiel #20
0
        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);
        }
        public PowershellPool(int poolSize, InitialSessionState initialSessionState, CancellationToken cancellationToken)
        {
            _poolMembers       = new List <PowerShellPoolMember>(poolSize);
            _processedCount    = 0;
            _cancellationToken = cancellationToken;

            for (var i = 0; i < poolSize; i++)
            {
                var powerShellPoolMember = new PowerShellPoolMember(this, i + 1);
                _poolMembers.Add(powerShellPoolMember);
                _availablePoolMembers.Add(powerShellPoolMember);
            }

            _runspacePool = RunspaceFactory.CreateRunspacePool(initialSessionState);
            _runspacePool.SetMaxRunspaces(poolSize);
        }
Beispiel #22
0
        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();
        }
Beispiel #23
0
        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);
        }
Beispiel #24
0
        public static PowerShellJob MakePowerShellJob <T>(Action <PowerShell> Configure,
                                                          Action <dynamic, List <T> > NewFunc, Func <List <T>, bool> SetList)
        {
            return(new PowerShellJob((runspacePool) =>
            {
                try
                {
                    var curList = new List <T>();
                    using (var localRunspacePool = RunspaceFactory.CreateRunspacePool())
                    {
                        localRunspacePool.Open();
                        using (var engine = PowerShell.Create())
                        {
                            engine.RunspacePool = localRunspacePool;
                            engine.AddScript(@"Import-Module RemoteDesktop");
                            engine.Commands.AddCommand("Import-Module").AddArgument("ActiveDirectory");
                            var importResult = engine.BeginInvoke();
                            var result = engine.EndInvoke(importResult);
                            Configure(engine);
                            var invokeResult = engine.BeginInvoke();
                            var commandIter = engine.EndInvoke(invokeResult);

                            if (engine.Streams.Error.Count > 0)
                            {
                                ErrorHelper.WriteErrorToEventLog(PowerShellJob.GetErrorMessage(engine.Streams.Error));
                                throw new Exception(PowerShellJob.GetErrorMessage(engine.Streams.Error));
                            }

                            foreach (dynamic psObject in commandIter)
                            {
                                NewFunc(psObject, curList);
                            }
                        }
                    }

                    return SetList(curList);
                }
                catch (Exception ex)
                {
                    ErrorHelper.WriteErrorToEventLog(ex.Message);
                }

                return false;
            }, true));
        }
Beispiel #25
0
        /// <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
                {
                    // Get the latest version of PSScriptAnalyzer we can find
                    pssaModuleInfo = ps.Invoke()?
                                     .Select(psObj => psObj.BaseObject)
                                     .OfType <PSModuleInfo>()
                                     .OrderByDescending(moduleInfo => moduleInfo.Version)
                                     .FirstOrDefault();
                }
                catch (Exception e)
                {
                    throw new AnalysisServiceLoadException("Unable to find PSScriptAnalyzer module on the module path", e);
                }

                if (pssaModuleInfo == null)
                {
                    throw new AnalysisServiceLoadException("Unable to find PSScriptAnalyzer module on the module path");
                }

                // Create a base session state with PSScriptAnalyzer loaded
                InitialSessionState sessionState;
                if (Environment.GetEnvironmentVariable("PSES_TEST_USE_CREATE_DEFAULT") == "1")
                {
                    sessionState = InitialSessionState.CreateDefault();
                }
                else
                {
                    sessionState = InitialSessionState.CreateDefault2();
                }
                sessionState.ImportPSModule(new [] { pssaModuleInfo.ModuleBase });

                // RunspacePool takes care of queuing commands for us so we do not
                // need to worry about executing concurrent commands
                return(RunspaceFactory.CreateRunspacePool(sessionState));
            }
        }
Beispiel #26
0
        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));
                }
            }
        }
Beispiel #27
0
        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();
        }
Beispiel #28
0
        static void Main(string[] args)
        {
            var connectionInfo = new WSManConnectionInfo()
            {
                Scheme       = "https",
                ComputerName = ConfigurationManager.AppSettings["ComputerName"],
                Port         = int.Parse(ConfigurationManager.AppSettings["Port"]),
                Credential   = new PSCredential(ConfigurationManager.AppSettings["UserName"],
                                                ConfigurationManager.AppSettings["Password"]
                                                .Aggregate(new SecureString(), (s, c) =>
                {
                    s.AppendChar(c);
                    return(s);
                })),
                SkipCACheck = true
            };

            using (var rsPool = RunspaceFactory.CreateRunspacePool(1, 2, connectionInfo))
            {
                rsPool.Open();

                var gpsCommand = PowerShell.Create().AddCommand("Get-Process");
                gpsCommand.RunspacePool = rsPool;
                var gpsCommandAsyncResult = gpsCommand.BeginInvoke();

                var getServiceCommand = PowerShell.Create().AddCommand("Get-Service");
                getServiceCommand.RunspacePool = rsPool;
                var getServiceCommandAsyncResult = getServiceCommand.BeginInvoke();

                var gpsCommandOutput = gpsCommand.EndInvoke(gpsCommandAsyncResult);
                gpsCommandOutput.Select(result => string.Format("{0} {1}", result.Properties["ID"].Value, result.Properties["Name"].Value))
                .ToList()
                .ForEach(Console.WriteLine);

                var getServiceCommandOutput = getServiceCommand.EndInvoke(getServiceCommandAsyncResult);
                getServiceCommandOutput.Select(result => string.Format("{0} {1}", result.Properties["Status"].Value, result.Properties["Name"].Value))
                .ToList()
                .ForEach(Console.WriteLine);

                rsPool.Close();
            }
            Console.ReadKey();
        }
Beispiel #29
0
        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 + "!");
        }
        public async Task <object> CreateRunspacePool(object input)
        {
            var inputDict = input as IDictionary <string, object>;

            if (inputDict == null)
            {
                throw new ArgumentException("input");
            }

            var runspaceKey   = (string)inputDict["RunspaceKey"];
            var startupScript = (string)inputDict["StartupScript"];

            if (runspacePools.ContainsKey(runspaceKey))
            {
                throw new InvalidOperationException("Runspace already created with key" + runspaceKey);
            }

            if (string.IsNullOrEmpty(startupScript))
            {
                // Assign a dummy script if not provided.
                startupScript = "Out-Null";
            }

            var initialState = InitialSessionState.CreateDefault();

            var          promptHandler = (Func <object, Task <object> >)inputDict["PromptHandler"];
            PSEdgeRawUI  rawUI         = new PSEdgeRawUI();
            PSEdgeHostUI hostUI        = new PSEdgeHostUI(rawUI, promptHandler);

            PSEdgeHost host = new PSEdgeHost(hostUI);

            // inject the startup script in the runspace so it is invoked automatically.
            initialState.Variables.Add(
                new SessionStateVariableEntry("orbPrivate_RunspaceStartupScript", startupScript, "", ScopedItemOptions.AllScope));

            var runspace = RunspaceFactory.CreateRunspacePool(MinRunspacesPerKey, MaxRunspacesPerKey, initialState, host);

            await Task.Factory.FromAsync(runspace.BeginOpen, runspace.EndOpen, null);

            runspacePools[runspaceKey] = runspace;

            return(true);
        }