예제 #1
0
        /// <summary>
        /// Runs a PowerShell script/command asynchronously.
        /// </summary>
        /// <param name="commandText">The text of the command to run.</param>
        /// <param name="callback">The callback function used to process the results of the asynchronous run.</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="input">[Optional] A collection of strings representing command-line input sent to the command/script during execution.</param>
        /// <param name="parameterList">A dictionary of additional parameters to supply to the PowerShell script/command.</param>
        public WaitHandle RunAsynchronously(string commandText, PowerShell.ProcessResults callback, Dictionary <String, Object> stateValues = null, PSDataCollection <string> input = null, params KeyValuePair <String, Object>[] parameterList)
        {
            // Run the script asynchronously.
            RunspacePool pool = RunspacePool;

            return(PowerShell.RunAsynchronously(commandText, ref pool, callback, Log, input, stateValues, parameterList));
        }
예제 #2
0
        private ScriptJob(object id, RunspacePool runspacePool, string scriptBlock, IEnumerable <object> args = null, bool useLocalScope = false)
        {
            if (runspacePool == null)
            {
                throw new ArgumentNullException("RunspacePool");
            }
            if (String.IsNullOrEmpty(scriptBlock))
            {
                throw new ArgumentNullException("ScriptBlock");
            }

            this.ID          = id;
            this.ScriptBlock = scriptBlock;
            this.Args        = args;

            this.Pipe = PowerShell.Create().AddScript(this.ScriptBlock, useLocalScope);

            if (this.Args != null)
            {
                foreach (var arg in this.Args)
                {
                    this.Pipe = this.Pipe.AddArgument(arg);
                }
            }
            this.Pipe.RunspacePool = runspacePool;
            this.AsyncResult       = this.Pipe.BeginInvoke();
        }
        // 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);
            }
        }
예제 #4
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();
        }
예제 #5
0
 public InvokeParallelTests()
 {
     _iss           = CreateInitialSessionState();
     m_runspacePool = RunspaceFactory.CreateRunspacePool(_iss);
     m_runspacePool.SetMaxRunspaces(10);
     m_runspacePool.Open();
 }
예제 #6
0
 public InvokeParameter(InvokeParameter other)
 {
     rsp                    = other.rsp;
     parameters             = other.parameters;
     cancelToken            = other.cancelToken;
     invocationStateChanged = other.invocationStateChanged;
 }
        /// <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();
                EnumeratePSScriptAnalyzerCmdlets();
                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());
            }
        }
예제 #8
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();
        }
예제 #9
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();
        }
예제 #10
0
파일: service.cs 프로젝트: rjmholt/misc
        public static ExamplePowerShellService Create(int maxRunspaces)
        {
            RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(minRunspaces: 1, maxRunspaces);

            runspacePool.Open();
            return(new ExamplePowerShellService(runspacePool));
        }
예제 #11
0
        /// <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();
        }
예제 #12
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();
 }
예제 #13
0
        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 static dynamic Dynamic(this RunspacePool pool)
 {
     if (pool == null)
     {
         return(new DynamicPowershell());
     }
     return(new DynamicPowershell(pool));
 }
예제 #15
0
 internal static Version GetPSRemotingProtocolVersion(RunspacePool rsPool)
 {
     if ((rsPool != null) && (rsPool.RemoteRunspacePoolInternal != null))
     {
         return(rsPool.RemoteRunspacePoolInternal.PSRemotingProtocolVersion);
     }
     return(null);
 }
예제 #16
0
        protected override void Dispose(bool disposing)
        {
            Stop();

            RunspacePool.Close();
            RunspacePool.Dispose();
            RunspacePool = null;
            base.Dispose(disposing);
        }
예제 #17
0
 private PssaCmdletAnalysisEngine(
     ILogger logger,
     RunspacePool analysisRunspacePool,
     PSModuleInfo pssaModuleInfo,
     string[] rulesToInclude)
     : this(logger, analysisRunspacePool, pssaModuleInfo)
 {
     _rulesToInclude = rulesToInclude;
 }
예제 #18
0
        // ---------- 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;
        }
예제 #19
0
 private PssaCmdletAnalysisEngine(
     ILogger logger,
     RunspacePool analysisRunspacePool,
     PSModuleInfo pssaModuleInfo)
 {
     _logger = logger;
     _analysisRunspacePool = analysisRunspacePool;
     _pssaModuleInfo       = pssaModuleInfo;
 }
예제 #20
0
 public DynamicPowershell(RunspacePool runspacePool)
 {
     _runspacePool = new AccessPrivateWrapper(runspacePool);
     if (_runspacePool.RunspacePoolStateInfo.State == RunspacePoolState.BeforeOpen)
     {
         _runspacePool.Open();
     }
     _runspaceIsOwned = false;
 }
 /// <summary>
 /// Disposes the runspace being used by the analysis service.
 /// </summary>
 public void Dispose()
 {
     if (this.analysisRunspacePool != null)
     {
         this.analysisRunspacePool.Close();
         this.analysisRunspacePool.Dispose();
         this.analysisRunspacePool = null;
     }
 }
예제 #22
0
 private PssaCmdletAnalysisEngine(
     ILogger logger,
     RunspacePool analysisRunspacePool,
     PSModuleInfo pssaModuleInfo,
     object analysisSettingsParameter)
     : this(logger, analysisRunspacePool, pssaModuleInfo)
 {
     _settingsParameter = analysisSettingsParameter;
 }
        /// <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);
                }
            }
        }
예제 #24
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);
            }
        }
예제 #25
0
        /// <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();
        }
예제 #27
0
        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);
        }
예제 #28
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);
            }
        }
예제 #29
0
        private bool _disposedValue = false; // To detect redundant calls

        /// <summary>
        /// Dispose of this object.
        /// </summary>
        /// <param name="disposing">True if the method is called by the Dispose method, false if called by the finalizer.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposedValue)
            {
                if (disposing)
                {
                    _analysisRunspacePool.Dispose();
                    _analysisRunspacePool = null;
                }

                _disposedValue = true;
            }
        }
예제 #30
0
 /// <summary>
 /// Construct a new AnalysisService object.
 /// </summary>
 /// <param name="analysisRunspacePool">
 /// The runspace pool with PSScriptAnalyzer module loaded that will handle
 /// analysis tasks.
 /// </param>
 /// <param name="pssaSettingsPath">
 /// The path to the PSScriptAnalyzer settings file to handle analysis settings.
 /// </param>
 /// <param name="activeRules">An array of rules to be used for analysis.</param>
 /// <param name="logger">Maintains logs for the analysis service.</param>
 /// <param name="pssaModuleInfo">
 /// Optional module info of the loaded PSScriptAnalyzer module. If not provided,
 /// the analysis service will populate it, but it can be given here to save time.
 /// </param>
 private AnalysisService(
     RunspacePool analysisRunspacePool,
     string pssaSettingsPath,
     IEnumerable <string> activeRules,
     ILogger logger,
     PSModuleInfo pssaModuleInfo = null)
 {
     _analysisRunspacePool = analysisRunspacePool;
     SettingsPath          = pssaSettingsPath;
     ActiveRules           = activeRules.ToArray();
     _logger         = logger;
     _pssaModuleInfo = pssaModuleInfo;
 }
예제 #31
0
        /// <summary>
        /// Creates an array of PowerShell objects that are in the Disconnected state for 
        /// all currently disconnected running commands associated with this runspace pool.
        /// </summary>
        /// <returns>Array of PowerShell objects.</returns>
        public override Collection<PowerShell> CreateDisconnectedPowerShells(RunspacePool runspacePool)
        {
            Collection<PowerShell> psCollection = new Collection<PowerShell>();

            if (ConnectCommands == null)
            {
                // Throw error indicating that this runspacepool is not configured for
                // reconstructing commands.
                string msg = StringUtil.Format(RunspacePoolStrings.CannotReconstructCommands, this.Name);
                throw new InvalidRunspacePoolStateException(msg);
            }

            // Get list of all disconnected commands associated with this runspace pool.
            foreach (ConnectCommandInfo connectCmdInfo in ConnectCommands)
            {
                psCollection.Add(new PowerShell(connectCmdInfo, runspacePool));
            }

            return psCollection;
        }
예제 #32
0
        internal static RunspacePool[] GetRemoteRunspacePools(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable)
        {
            WSManConnectionInfo wsmanConnectionInfoParam = connectionInfo as WSManConnectionInfo;

            // Disconnect-Connect currently only supported by WSMan.
            if (wsmanConnectionInfoParam == null)
            {
                throw new NotSupportedException();
            }

            List<RunspacePool> discRunspacePools = new List<RunspacePool>();

            // Enumerate all runspacepools
            Collection<PSObject> runspaceItems = RemoteRunspacePoolEnumeration.GetRemotePools(wsmanConnectionInfoParam);
            foreach (PSObject rsObject in runspaceItems)
            {
                // Create a new WSMan connection info object for each returned runspace pool.
                WSManConnectionInfo wsmanConnectionInfo = wsmanConnectionInfoParam.Copy();

                PSPropertyInfo pspShellId = rsObject.Properties["ShellId"];
                PSPropertyInfo pspState = rsObject.Properties["State"];
                PSPropertyInfo pspName = rsObject.Properties["Name"];
                PSPropertyInfo pspResourceUri = rsObject.Properties["ResourceUri"];

                if (pspShellId == null || pspState == null || pspName == null || pspResourceUri == null)
                {
                    continue;
                }

                string strName = pspName.Value.ToString();
                string strShellUri = pspResourceUri.Value.ToString();
                bool isDisconnected = pspState.Value.ToString().Equals("Disconnected", StringComparison.OrdinalIgnoreCase);
                Guid shellId = Guid.Parse(pspShellId.Value.ToString());

                // Filter returned items for PowerShell sessions.
                if (strShellUri.StartsWith(WSManNativeApi.ResourceURIPrefix, StringComparison.OrdinalIgnoreCase) == false)
                {
                    continue;
                }

                // Update wsmanconnection information with server settings.
                UpdateWSManConnectionInfo(wsmanConnectionInfo, rsObject);
                // Ensure that EnableNetworkAccess property is always enabled for reconstructed runspaces.
                wsmanConnectionInfo.EnableNetworkAccess = true;

                // Compute runspace DisconnectedOn and ExpiresOn fields.
                if (isDisconnected)
                {
                    DateTime? disconnectedOn;
                    DateTime? expiresOn;
                    ComputeDisconnectedOnExpiresOn(rsObject, out disconnectedOn, out expiresOn);
                    wsmanConnectionInfo.DisconnectedOn = disconnectedOn;
                    wsmanConnectionInfo.ExpiresOn = expiresOn;
                }

                List<ConnectCommandInfo> connectCmdInfos = new List<ConnectCommandInfo>();

                // Enumerate all commands on runspace pool.
                Collection<PSObject> commandItems;
                try
                {
                    commandItems = RemoteRunspacePoolEnumeration.GetRemoteCommands(shellId, wsmanConnectionInfo);
                }
                catch (CmdletInvocationException e)
                {
                    if (e.InnerException != null && e.InnerException is InvalidOperationException)
                    {
                        // If we cannot successfully retrieve command information then this runspace
                        // object we are building is invalid and must be skipped.
                        continue;
                    }

                    throw;
                }
                foreach (PSObject cmdObject in commandItems)
                {
                    PSPropertyInfo pspCommandId = cmdObject.Properties["CommandId"];
                    PSPropertyInfo pspCommandLine = cmdObject.Properties["CommandLine"];

                    if (pspCommandId == null)
                    {
                        Dbg.Assert(false, "Should not get an empty command Id from a remote runspace pool.");
                        continue;
                    }

                    string cmdLine = (pspCommandLine != null) ? pspCommandLine.Value.ToString() : string.Empty;
                    Guid cmdId = Guid.Parse(pspCommandId.Value.ToString());

                    connectCmdInfos.Add(new ConnectCommandInfo(cmdId, cmdLine));
                }

                // At this point we don't know if the runspace pool we want to connect to has just one runspace
                // (a RemoteRunspace/PSSession) or multiple runspaces in its pool.  We do have an array of 
                // running command information which will indicate a runspace pool if the count is gt one.
                RunspacePool runspacePool = new RunspacePool(isDisconnected, shellId, strName,
                    connectCmdInfos.ToArray(), wsmanConnectionInfo, host, typeTable);
                discRunspacePools.Add(runspacePool);
            }

            return discRunspacePools.ToArray();
        }
예제 #33
0
 /// <summary>
 /// Creates an array of PowerShell objects that are in the Disconnected state for 
 /// all currently disconnected running commands associated with this runspace pool.
 /// </summary>
 /// <returns></returns>
 public virtual Collection<PowerShell> CreateDisconnectedPowerShells(RunspacePool runspacePool)
 {
     throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceDisconnectConnectNotSupported);
 }