예제 #1
1
        public PSTestScope(bool connect = true)
        {
            SiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"];
            CredentialManagerEntry = ConfigurationManager.AppSettings["SPOCredentialManagerLabel"];

            var iss = InitialSessionState.CreateDefault();
            if (connect)
            {
                SessionStateCmdletEntry ssce = new SessionStateCmdletEntry("Connect-SPOnline", typeof(ConnectSPOnline), null);

                iss.Commands.Add(ssce);
            }
            _runSpace = RunspaceFactory.CreateRunspace(iss);

            _runSpace.Open();

            if (connect)
            {
                var pipeLine = _runSpace.CreatePipeline();
                Command cmd = new Command("connect-sponline");
                cmd.Parameters.Add("Url", SiteUrl);
                if (!string.IsNullOrEmpty(CredentialManagerEntry))
                {
                    cmd.Parameters.Add("Credentials", CredentialManagerEntry);
                }
                pipeLine.Commands.Add(cmd);
                pipeLine.Invoke();
            }
        }
예제 #2
0
 public override InitialSessionStateEntry Clone()
 {
     SessionStateCmdletEntry entry = new SessionStateCmdletEntry(base.Name, this._implementingType, this._helpFileName, base.Visibility);
     entry.SetPSSnapIn(base.PSSnapIn);
     entry.SetModule(base.Module);
     return entry;
 }
예제 #3
0
 internal void AddSessionStateCmdletEntryToCache(SessionStateCmdletEntry entry, bool local)
 {
     if (!this.IsSpecialCmdlet(entry.ImplementingType))
     {
         CmdletInfo newCmdletInfo = this.NewCmdletInfo(entry);
         this.AddCmdletInfoToCache(newCmdletInfo.Name, newCmdletInfo, !local);
     }
 }
예제 #4
0
        public override InitialSessionStateEntry Clone()
        {
            SessionStateCmdletEntry entry = new SessionStateCmdletEntry(base.Name, this._implementingType, this._helpFileName, base.Visibility);

            entry.SetPSSnapIn(base.PSSnapIn);
            entry.SetModule(base.Module);
            return(entry);
        }
예제 #5
0
        public PSTestScope(bool connect = true)
        {
            SiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"];
            CredentialManagerEntry = ConfigurationManager.AppSettings["SPOCredentialManagerLabel"];
            Realm = ConfigurationManager.AppSettings["Realm"];
            AppId = ConfigurationManager.AppSettings["AppId"];
            AppSecret = ConfigurationManager.AppSettings["AppSecret"];

            var iss = InitialSessionState.CreateDefault();
            if (connect)
            {
                SessionStateCmdletEntry ssce = new SessionStateCmdletEntry("Connect-PnPOnline", typeof(ConnectOnline), null);

                iss.Commands.Add(ssce);
            }
            _runSpace = RunspaceFactory.CreateRunspace(iss);

            _runSpace.Open();

            // Sets the execution policy to unrestricted. Requires Visual Studio to run in elevated mode.
            var pipeLine = _runSpace.CreatePipeline();
            Command cmd = new Command("Set-ExecutionPolicy");
            cmd.Parameters.Add("ExecutionPolicy", "Unrestricted");
            cmd.Parameters.Add("Scope", "Process");
            pipeLine.Commands.Add(cmd);
            pipeLine.Invoke();

            if (connect)
            {
                pipeLine = _runSpace.CreatePipeline();
                cmd = new Command("connect-pnponline");
                cmd.Parameters.Add("Url", SiteUrl);
                if (!string.IsNullOrEmpty(CredentialManagerEntry))
                {
                    // Use Windows Credential Manager to authenticate
                    cmd.Parameters.Add("Credentials", CredentialManagerEntry);
                }
                else
                {
                    if (!string.IsNullOrEmpty("AppId") && !string.IsNullOrEmpty("AppSecret"))
                    {
                        // Use oAuth Token to authenticate
                        if (!string.IsNullOrEmpty(Realm))
                        {
                            cmd.Parameters.Add("Realm", Realm);
                        }
                        cmd.Parameters.Add("AppId", AppId);
                        cmd.Parameters.Add("AppSecret", AppSecret);
                    }
                }
                pipeLine.Commands.Add(cmd);
                pipeLine.Invoke();
            }
        }
예제 #6
0
        /// <summary>
        /// This sample shows how to add a cmdlet to an InitialSessionState object and then 
        /// uses the modified InitialSessionState object when creating a Runspace object.
        /// </summary>
        /// <param name="args">Parameter is not used.</param>
        /// This sample demonstrates:
        /// 1. Creating an InitialSessionState object.
        /// 2. Adding a cmdlet to the InitialSessionState object.
        /// 3. Creating a runspace that uses the InitialSessionState object.
        /// 4. Craeting a PowerShell object tht uses the Runspace object.
        /// 5. Running the pipeline of the PowerShell object synchronously.
        /// 6. Working with PSObject objects to extract properties 
        ///    from the objects returned by the pipeline.
        private static void Main(string[] args)
        {
            // Create a default InitialSessionState object. The default
              // InitialSessionState object contains all the elements provided
              // by Windows PowerShell.
              InitialSessionState iss = InitialSessionState.CreateDefault();

              // Add the get-proc cmdlet to the InitialSessionState object.
              SessionStateCmdletEntry ssce = new SessionStateCmdletEntry("get-proc", typeof(GetProcCommand), null);
              iss.Commands.Add(ssce);

              // Create a Runspace object that uses the InitialSessionState object.
              // Notice that no PSHost object is specified, so the default host is used.
              // See the Hosting samples for information on creating your own custom host.
              using (Runspace myRunSpace = RunspaceFactory.CreateRunspace(iss))
              {
            myRunSpace.Open();

            using (PowerShell powershell = PowerShell.Create())
            {
              powershell.Runspace = myRunSpace;

              // Add the get-proc cmdlet to the pipeline of the PowerShell object.
              powershell.AddCommand("get-proc");

              Collection<PSObject> results = powershell.Invoke();

              Console.WriteLine("Process              HandleCount");
              Console.WriteLine("--------------------------------");

              // Display the output of the pipeline.
              foreach (PSObject result in results)
              {
             Console.WriteLine(
                               "{0,-20} {1}",
                               result.Members["ProcessName"].Value,
                               result.Members["HandleCount"].Value);
              }
            }

            // Close the runspace to release resources.
            myRunSpace.Close();
              }

              System.Console.WriteLine("Hit any key to exit...");
              System.Console.ReadKey();
        }
예제 #7
0
        public PSTestScope(bool connect = true)
        {
            SiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"];
            CredentialManagerEntry = ConfigurationManager.AppSettings["SPOCredentialManagerLabel"];
            Realm = ConfigurationManager.AppSettings["Realm"];
            AppId = ConfigurationManager.AppSettings["AppId"];
            AppSecret = ConfigurationManager.AppSettings["AppSecret"];

            var iss = InitialSessionState.CreateDefault();
            if (connect)
            {
                SessionStateCmdletEntry ssce = new SessionStateCmdletEntry("Connect-SPOnline", typeof(ConnectSPOnline), null);

                iss.Commands.Add(ssce);
            }
            _runSpace = RunspaceFactory.CreateRunspace(iss);

            _runSpace.Open();


            if (connect)
            {
                var pipeLine = _runSpace.CreatePipeline();
                Command cmd = new Command("connect-sponline");
                cmd.Parameters.Add("Url", SiteUrl);
                if (!string.IsNullOrEmpty(CredentialManagerEntry))
                {
                    // Use Windows Credential Manager to authenticate
                    cmd.Parameters.Add("Credentials", CredentialManagerEntry);
                }
                else
                {                    
                    if (!string.IsNullOrEmpty(Realm) && !string.IsNullOrEmpty("AppId") && !string.IsNullOrEmpty("AppSecret"))
                    {
                        // Use oAuth Token to authenticate
                        cmd.Parameters.Add("Realm", Realm);
                        cmd.Parameters.Add("AppId", AppId);
                        cmd.Parameters.Add("AppSecret", AppSecret);
                    }
                }
                pipeLine.Commands.Add(cmd);
                pipeLine.Invoke();
            }
        }
예제 #8
0
        /// <summary>
        /// Sample adds a cmdlet to InitialSessionState and then uses 
        /// modified InitialSessionState to create the Runspace.
        /// </summary>
        /// <param name="args">Unused</param>
        static void Main(string[] args)
        {
            //Create a default InitialSessionState
            InitialSessionState iss = InitialSessionState.CreateDefault();
            //Add get-proc cmdlet to the session state
            SessionStateCmdletEntry ssce = new SessionStateCmdletEntry("get-proc", typeof(GetProcCommand), null);
            iss.Commands.Add(ssce);

            // Create a runspace.
            // (Note that no PSHost instance is supplied in the constructor so the
            // default PSHost implementation is used. See the Hosting topics for
            // more information on creating your own PSHost class.)

            Runspace myRunSpace = RunspaceFactory.CreateRunspace(iss);
            myRunSpace.Open();

            PowerShell powershell = PowerShell.Create();
            powershell.Runspace = myRunSpace;

            // Create a pipeline with get-proc command (from this assembly)
            powershell.AddCommand("get-proc");

            Collection<PSObject> results = powershell.Invoke();

            Console.WriteLine("Process              HandleCount");
            Console.WriteLine("--------------------------------");

            // Print out each result object...
            foreach (PSObject result in results)
            {
                Console.WriteLine("{0,-20} {1}",
                    result.Members["ProcessName"].Value,
                    result.Members["HandleCount"].Value);
            }

            // Finally close the runspace
            // up any resources.
            myRunSpace.Close();

            System.Console.WriteLine("Hit any key to exit...");
            System.Console.ReadKey();
        }
        public IDictionary<string, object> GetConfigValues(string filePath)
        {
            var scriptText = File.ReadAllText(filePath);
            var iss = InitialSessionState.CreateDefault();
            var importConfig = new SessionStateCmdletEntry("import-config", typeof (ImportConfigCommand), null);
            iss.Commands.Add(importConfig);

            iss.Providers.Add(new SessionStateProviderEntry("teamConfig", typeof (TeamConfigProvider), ""));
            var rs = RunspaceFactory.CreateRunspace(iss);
            rs.Open();
            rs.SessionStateProxy.Path.SetLocation(Path.GetDirectoryName(filePath));
            rs.SessionStateProxy.LanguageMode = PSLanguageMode.FullLanguage;

            var ps = PowerShell.Create();
            ps.Runspace = rs;
            ps.AddScript(scriptText);
            ps.Invoke();
            rs.Close();

            return new Dictionary<string, object>(TeamConfigProvider.ConfigValues);
        }
예제 #10
0
 internal static void AnalyzePSSnapInAssembly(
     Assembly assembly,
     string name,
     PSSnapInInfo psSnapInInfo,
     out Dictionary <string, SessionStateCmdletEntry> cmdlets,
     out Dictionary <string, SessionStateProviderEntry> providers)
 {
     if (assembly == null)
     {
         throw new ArgumentNullException(nameof(assembly));
     }
     if (PSSnapInHelpers._cmdletCache != null && PSSnapInHelpers._providerCache != null && (PSSnapInHelpers._cmdletCache.ContainsKey(assembly) && PSSnapInHelpers._providerCache.ContainsKey(assembly)))
     {
         cmdlets   = PSSnapInHelpers._cmdletCache[assembly];
         providers = PSSnapInHelpers._providerCache[assembly];
     }
     else
     {
         cmdlets   = (Dictionary <string, SessionStateCmdletEntry>)null;
         providers = (Dictionary <string, SessionStateProviderEntry>)null;
         PSSnapInHelpers._PSSnapInTracer.WriteLine("Analyzing assembly {0} for cmdlet and providers", (object)assembly.Location);
         string helpFile = PSSnapInHelpers.GetHelpFile(assembly.Location);
         Type[] types;
         try
         {
             types = assembly.GetTypes();
         }
         catch (ReflectionTypeLoadException ex)
         {
             string str = ex.Message + "\nLoader Exceptions: \n";
             if (ex.LoaderExceptions != null)
             {
                 foreach (Exception loaderException in ex.LoaderExceptions)
                 {
                     str = str + "\n" + loaderException.Message;
                 }
             }
             PSSnapInHelpers._PSSnapInTracer.TraceError(str);
             throw new PSSnapInException(name, str);
         }
         foreach (Type type in types)
         {
             if ((type.IsPublic || type.IsNestedPublic) && !type.IsAbstract)
             {
                 object[] customAttributes = type.GetCustomAttributes(false);
                 string   str1             = (string)null;
                 string   str2             = (string)null;
                 foreach (object obj in customAttributes)
                 {
                     if (obj.GetType() == typeof(CmdletAttribute))
                     {
                         str1 = PSSnapInHelpers.GetCmdletName(obj as CmdletAttribute);
                         break;
                     }
                     if (obj.GetType() == typeof(CmdletProviderAttribute))
                     {
                         str2 = PSSnapInHelpers.GetProviderName(obj as CmdletProviderAttribute);
                         break;
                     }
                 }
                 if (!string.IsNullOrEmpty(str1))
                 {
                     if (PSSnapInHelpers.IsCmdletClass(type) && PSSnapInHelpers.HasDefaultConstructor(type))
                     {
                         if (cmdlets != null && cmdlets.ContainsKey(str1))
                         {
                             string str3 = ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "PSSnapInDuplicateCmdlets", (object)str1, (object)name);
                             PSSnapInHelpers._PSSnapInTracer.TraceError(str3);
                             throw new PSSnapInException(name, str3);
                         }
                         SessionStateCmdletEntry stateCmdletEntry = new SessionStateCmdletEntry(str1, type, helpFile);
                         if (psSnapInInfo != null)
                         {
                             stateCmdletEntry.SetPSSnapIn(psSnapInInfo);
                         }
                         if (cmdlets == null)
                         {
                             cmdlets = new Dictionary <string, SessionStateCmdletEntry>((IEqualityComparer <string>)StringComparer.OrdinalIgnoreCase);
                         }
                         cmdlets.Add(str1, stateCmdletEntry);
                         PSSnapInHelpers._PSSnapInTracer.WriteLine("{0} from type {1} is added as a cmdlet. ", (object)str1, (object)type.FullName);
                         continue;
                     }
                     PSSnapInHelpers._PSSnapInTracer.TraceWarning("{0} is not valid cmdlet because it doesn't derive from the Cmdlet type or it doesn't have a default constructor.", (object)str1);
                 }
                 if (!string.IsNullOrEmpty(str2))
                 {
                     if (PSSnapInHelpers.IsProviderClass(type) && PSSnapInHelpers.HasDefaultConstructor(type))
                     {
                         if (providers != null && providers.ContainsKey(str2))
                         {
                             string str3 = ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "PSSnapInDuplicateProviders", (object)str2, (object)psSnapInInfo.Name);
                             PSSnapInHelpers._PSSnapInTracer.TraceError(str3);
                             throw new PSSnapInException(psSnapInInfo.Name, str3);
                         }
                         SessionStateProviderEntry stateProviderEntry = new SessionStateProviderEntry(str2, type, helpFile);
                         stateProviderEntry.SetPSSnapIn(psSnapInInfo);
                         if (providers == null)
                         {
                             providers = new Dictionary <string, SessionStateProviderEntry>((IEqualityComparer <string>)StringComparer.OrdinalIgnoreCase);
                         }
                         providers.Add(str2, stateProviderEntry);
                         PSSnapInHelpers._PSSnapInTracer.WriteLine("{0} from type {1} is added as a provider. ", (object)str2, (object)type.FullName);
                     }
                     else
                     {
                         PSSnapInHelpers._PSSnapInTracer.TraceWarning("{0} is not valid provider because it doesn't derive from the provider type or it doesn't have a default constructor.", (object)str2);
                     }
                 }
             }
         }
         lock (PSSnapInHelpers._syncObject)
         {
             if (cmdlets != null)
             {
                 if (PSSnapInHelpers._cmdletCache == null)
                 {
                     PSSnapInHelpers._cmdletCache = new Dictionary <Assembly, Dictionary <string, SessionStateCmdletEntry> >();
                 }
                 PSSnapInHelpers._cmdletCache[assembly] = cmdlets;
             }
             if (providers == null)
             {
                 return;
             }
             if (PSSnapInHelpers._providerCache == null)
             {
                 PSSnapInHelpers._providerCache = new Dictionary <Assembly, Dictionary <string, SessionStateProviderEntry> >();
             }
             PSSnapInHelpers._providerCache[assembly] = providers;
         }
     }
 }
예제 #11
0
 internal void AddSessionStateCmdletEntryToCache(SessionStateCmdletEntry entry)
 {
     this.AddSessionStateCmdletEntryToCache(entry, false);
 }
예제 #12
0
 /// <summary>
 /// Add an new SessionState cmdlet entry to this session state object...
 /// </summary>
 /// <param name="entry">The entry to add</param>
 internal void AddSessionStateEntry(SessionStateCmdletEntry entry)
 {
     AddSessionStateEntry(entry, /*local*/false);
 }
예제 #13
0
 private CmdletInfo NewCmdletInfo(SessionStateCmdletEntry entry)
 {
     return NewCmdletInfo(entry, this._context);
 }
예제 #14
0
 internal static CmdletInfo NewCmdletInfo(SessionStateCmdletEntry entry, ExecutionContext context)
 {
     CmdletInfo info = new CmdletInfo(entry.Name, entry.ImplementingType, entry.HelpFileName, entry.PSSnapIn, context) {
         Visibility = entry.Visibility
     };
     info.SetModule(entry.Module);
     return info;
 }
예제 #15
0
        /// <summary>
        /// This sample uses the ProxyCommand class to create a proxy command that 
        /// calls an existing cmdlet, but restricts the set of available parameters.  
        /// The proxy command is then added to an intial session state that is used to 
        /// create a contrained runspace. This means that the user can access the cmdlet 
        /// through the proxy command.
        /// </summary>
        /// <remarks>
        /// This sample demonstrates the following:
        /// 1. Creating a CommandMetadata object that describes the metadata of an 
        ///    existing cmdlet.
        /// 2. Modifying the cmdlet metadata to remove a parameter of the cmdlet.
        /// 3. Adding the cmdlet to an initial session state and making it private.
        /// 4. Creating a proxy function that calls the existing cmdlet, but exposes 
        ///    only a restricted set of parameters.   
        /// 6. Adding the proxy function to the initial session state. 
        /// 7. Calling the private cmdlet and the proxy function to demonstrate the 
        ///    constrained runspace.
        /// </remarks>
        private static void Main()
        {
            // Create a default intial session state. The default inital session state
              // includes all the elements that are provided by Windows PowerShell.
              InitialSessionState iss = InitialSessionState.CreateDefault();

              // Add the get-proc cmdlet to the initial session state.
              SessionStateCmdletEntry cmdletEntry = new SessionStateCmdletEntry("get-proc", typeof(GetProcCommand), null);
              iss.Commands.Add(cmdletEntry);

              // Make the cmdlet private so that it is not accessable.
              cmdletEntry.Visibility = SessionStateEntryVisibility.Private;

              // Set the language mode of the intial session state to NoLanguge to
              //prevent users from using language features. Only the invocation of
              // public commands is allowed.
              iss.LanguageMode = PSLanguageMode.NoLanguage;

              // Create the proxy command using cmdlet metadata to expose the
              // get-proc cmdlet.
              CommandMetadata cmdletMetadata = new CommandMetadata(typeof(GetProcCommand));

              // Remove one of the parameters from the command metadata.
              cmdletMetadata.Parameters.Remove("Name");

              // Generate the body of a proxy function that calls the original cmdlet,
              // but does not have the removed parameter.
              string bodyOfProxyFunction = ProxyCommand.Create(cmdletMetadata);

              // Add the proxy function to the initial session state. The name of the proxy
              // function can be the same as the name of the cmdlet, but to clearly
              // demonstrate that the original cmdlet is not available a different name is
              // used for the proxy function.
              iss.Commands.Add(new SessionStateFunctionEntry("get-procProxy", bodyOfProxyFunction));

              // Create the constrained runspace using the intial session state.
              using (Runspace myRunspace = RunspaceFactory.CreateRunspace(iss))
              {
            myRunspace.Open();

            // Call the private cmdlet to demonstrate that it is not available.
            try
            {
              using (PowerShell powershell = PowerShell.Create())
              {
            powershell.Runspace = myRunspace;
            powershell.AddCommand("get-proc").AddParameter("Name", "*explore*");
            powershell.Invoke();
              }
            }
            catch (CommandNotFoundException e)
            {
              System.Console.WriteLine(
                        "Invoking 'get-proc' failed as expected: {0}: {1}",
                        e.GetType().FullName,
                        e.Message);
            }

            // Call the proxy function to demonstrate that the -Name parameter is
            // not available.
            try
            {
              using (PowerShell powershell = PowerShell.Create())
              {
            powershell.Runspace = myRunspace;
            powershell.AddCommand("get-procProxy").AddParameter("Name", "idle");
            powershell.Invoke();
              }
            }
            catch (ParameterBindingException e)
            {
              System.Console.WriteLine(
                        "\nInvoking 'get-procProxy -Name idle' failed as expected: {0}: {1}",
                        e.GetType().FullName,
                        e.Message);
            }

            // Call the proxy function to demonstrate that it calls into the
            // private cmdlet to retrieve the processes.
            using (PowerShell powershell = PowerShell.Create())
            {
              powershell.Runspace = myRunspace;
              powershell.AddCommand("get-procProxy");
              List<Process> processes = new List<Process>(powershell.Invoke<Process>());
              System.Console.WriteLine(
                        "\nInvoking the get-procProxy function called into the get-proc cmdlet and returned {0} processes",
                        processes.Count);
            }

            // Close the runspace to release resources.
            myRunspace.Close();
              }

              System.Console.WriteLine("Hit any key to exit...");
              System.Console.ReadKey();
        }
예제 #16
0
 internal void AddSessionStateEntry(SessionStateCmdletEntry entry)
 {
     this.AddSessionStateEntry(entry, false);
 }
예제 #17
0
 internal void AddSessionStateEntry(SessionStateCmdletEntry entry, bool local)
 {
     this.ExecutionContext.CommandDiscovery.AddSessionStateCmdletEntryToCache(entry, local);
 }
        public static InitialSessionState GetSessionStateForCommands(CommandInfo[] commands)
        {
            InitialSessionState iss = InitialSessionState.CreateDefault();
            Dictionary<string, SessionStateCommandEntry> commandCache = new Dictionary<string, SessionStateCommandEntry>();
            foreach (SessionStateCommandEntry ssce in iss.Commands)
            {
                commandCache[ssce.Name] = ssce;
            }
            iss.ApartmentState = ApartmentState.STA;
            iss.ThreadOptions = PSThreadOptions.ReuseThread;
            if (commands.Length == 0)
            {
                return iss;
            }
            foreach (CommandInfo cmd in commands)
            {
                if (cmd.Module != null)
                {
                    if (cmd.ModuleName == "WPK")
                    {
                        if (cmd is AliasInfo)
                        {
                            SessionStateAliasEntry alias = new SessionStateAliasEntry(cmd.Name, cmd.Definition);
                            iss.Commands.Add(alias);
                            continue;
                        }
                        if (cmd is FunctionInfo)
                        {
                            SessionStateFunctionEntry func = new SessionStateFunctionEntry(cmd.Name, cmd.Definition);
                            iss.Commands.Add(func);
                            continue;
                        }
                        if (cmd is CmdletInfo)
                        {
                            CmdletInfo cmdletData = cmd as CmdletInfo;
                            SessionStateCmdletEntry cmdlet = new SessionStateCmdletEntry(cmd.Name,
                                cmdletData.ImplementingType,
                                cmdletData.HelpFile);
                            iss.Commands.Add(cmdlet);
                        }

                    }
                    else
                    {
                    
                        string manifestPath = cmd.Module.Path.Replace(".psm1",".psd1").Replace(".dll", ".psd1");
                        if (System.IO.File.Exists(manifestPath)) {  
                            iss.ImportPSModule(new string[] { manifestPath });
                        } else {
                            iss.ImportPSModule(new string[] { cmd.Module.Path });
                        }
                        
                        continue;
                    }
                }
                if (cmd is AliasInfo)
                {
                    CommandInfo loopCommand = cmd;
                    while (loopCommand is AliasInfo)
                    {
                        SessionStateAliasEntry alias = new SessionStateAliasEntry(loopCommand.Name, loopCommand.Definition);
                        iss.Commands.Add(alias);
                        loopCommand = (loopCommand as AliasInfo).ReferencedCommand;
                    }
                    if (loopCommand is FunctionInfo)
                    {
                        SessionStateFunctionEntry func = new SessionStateFunctionEntry(loopCommand.Name, loopCommand.Definition);
                        iss.Commands.Add(func);
                    }
                    if (loopCommand is CmdletInfo)
                    {
                        CmdletInfo cmdletData = loopCommand as CmdletInfo;
                        SessionStateCmdletEntry cmdlet = new SessionStateCmdletEntry(cmd.Name,
                                cmdletData.ImplementingType,
                                cmdletData.HelpFile);
                        iss.Commands.Add(cmdlet);
                    }
                }
                if (cmd is FunctionInfo)
                {
                    SessionStateFunctionEntry func = new SessionStateFunctionEntry(cmd.Name, cmd.Definition);
                    iss.Commands.Add(func);
                }
                if (cmd is CmdletInfo)
                {
                    CmdletInfo cmdletData = cmd as CmdletInfo;
                    SessionStateCmdletEntry cmdlet = new SessionStateCmdletEntry(cmd.Name,
                            cmdletData.ImplementingType,
                            cmdletData.HelpFile);
                    iss.Commands.Add(cmdlet);
                }
            }
            return iss;
        }
예제 #19
0
 internal static void AnalyzePSSnapInAssembly(Assembly assembly, string name, PSSnapInInfo psSnapInInfo, PSModuleInfo moduleInfo, bool isModuleLoad, out Dictionary <string, SessionStateCmdletEntry> cmdlets, out Dictionary <string, SessionStateProviderEntry> providers, out string helpFile)
 {
     Type[] assemblyTypes;
     helpFile = null;
     if (assembly == null)
     {
         throw new ArgumentNullException("assembly");
     }
     cmdlets   = null;
     providers = null;
     if (_cmdletCache.Value.ContainsKey(assembly))
     {
         cmdlets = new Dictionary <string, SessionStateCmdletEntry>(_cmdletCache.Value.Count, StringComparer.OrdinalIgnoreCase);
         Dictionary <string, SessionStateCmdletEntry> dictionary = _cmdletCache.Value[assembly];
         foreach (string str in dictionary.Keys)
         {
             SessionStateCmdletEntry entry = dictionary[str];
             if ((entry.PSSnapIn == null) && (psSnapInInfo != null))
             {
                 entry.SetPSSnapIn(psSnapInInfo);
             }
             SessionStateCmdletEntry entry2 = (SessionStateCmdletEntry)entry.Clone();
             cmdlets[str] = entry2;
         }
     }
     if (_providerCache.Value.ContainsKey(assembly))
     {
         providers = new Dictionary <string, SessionStateProviderEntry>(_providerCache.Value.Count, StringComparer.OrdinalIgnoreCase);
         Dictionary <string, SessionStateProviderEntry> dictionary2 = _providerCache.Value[assembly];
         foreach (string str2 in dictionary2.Keys)
         {
             SessionStateProviderEntry entry3 = dictionary2[str2];
             if ((entry3.PSSnapIn == null) && (psSnapInInfo != null))
             {
                 entry3.SetPSSnapIn(psSnapInInfo);
             }
             SessionStateProviderEntry entry4 = (SessionStateProviderEntry)entry3.Clone();
             providers[str2] = entry4;
         }
     }
     if ((cmdlets != null) || (providers != null))
     {
         if (!_assembliesWithModuleInitializerCache.Value.ContainsKey(assembly))
         {
             _PSSnapInTracer.WriteLine("Returning cached cmdlet and provider entries for {0}", new object[] { assembly.Location });
         }
         else
         {
             _PSSnapInTracer.WriteLine("Executing IModuleAssemblyInitializer.Import for {0}", new object[] { assembly.Location });
             assemblyTypes = GetAssemblyTypes(assembly, name);
             ExecuteModuleInitializer(assembly, assemblyTypes, isModuleLoad);
         }
     }
     else
     {
         _PSSnapInTracer.WriteLine("Analyzing assembly {0} for cmdlet and providers", new object[] { assembly.Location });
         helpFile      = GetHelpFile(assembly.Location);
         assemblyTypes = GetAssemblyTypes(assembly, name);
         ExecuteModuleInitializer(assembly, assemblyTypes, isModuleLoad);
         Type type  = null;
         Type type2 = null;
         foreach (Type type3 in assemblyTypes)
         {
             if ((type3.IsPublic || type3.IsNestedPublic) && !type3.IsAbstract)
             {
                 if (IsCmdletClass(type3) && HasDefaultConstructor(type3))
                 {
                     type = type3;
                     CmdletAttribute customAttribute = GetCustomAttribute <CmdletAttribute>(type3);
                     if (customAttribute != null)
                     {
                         string cmdletName = GetCmdletName(customAttribute);
                         if (!string.IsNullOrEmpty(cmdletName))
                         {
                             if ((cmdlets != null) && cmdlets.ContainsKey(cmdletName))
                             {
                                 string errorMessageFormat = StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInDuplicateCmdlets, cmdletName, name);
                                 _PSSnapInTracer.TraceError(errorMessageFormat, new object[0]);
                                 throw new PSSnapInException(name, errorMessageFormat);
                             }
                             SessionStateCmdletEntry entry5 = new SessionStateCmdletEntry(cmdletName, type3, helpFile);
                             if (psSnapInInfo != null)
                             {
                                 entry5.SetPSSnapIn(psSnapInInfo);
                             }
                             if (cmdlets == null)
                             {
                                 cmdlets = new Dictionary <string, SessionStateCmdletEntry>(StringComparer.OrdinalIgnoreCase);
                             }
                             cmdlets.Add(cmdletName, entry5);
                             _PSSnapInTracer.WriteLine("{0} from type {1} is added as a cmdlet. ", new object[] { cmdletName, type3.FullName });
                         }
                     }
                 }
                 else if (IsProviderClass(type3) && HasDefaultConstructor(type3))
                 {
                     type2 = type3;
                     CmdletProviderAttribute providerAttribute = GetCustomAttribute <CmdletProviderAttribute>(type3);
                     if (providerAttribute != null)
                     {
                         string providerName = GetProviderName(providerAttribute);
                         if (!string.IsNullOrEmpty(providerName))
                         {
                             if ((providers != null) && providers.ContainsKey(providerName))
                             {
                                 string str6 = StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInDuplicateProviders, providerName, psSnapInInfo.Name);
                                 _PSSnapInTracer.TraceError(str6, new object[0]);
                                 throw new PSSnapInException(psSnapInInfo.Name, str6);
                             }
                             SessionStateProviderEntry entry6 = new SessionStateProviderEntry(providerName, type3, helpFile);
                             entry6.SetPSSnapIn(psSnapInInfo);
                             if (moduleInfo != null)
                             {
                                 entry6.SetModule(moduleInfo);
                             }
                             if (providers == null)
                             {
                                 providers = new Dictionary <string, SessionStateProviderEntry>(StringComparer.OrdinalIgnoreCase);
                             }
                             providers.Add(providerName, entry6);
                             _PSSnapInTracer.WriteLine("{0} from type {1} is added as a provider. ", new object[] { providerName, type3.FullName });
                         }
                     }
                 }
             }
         }
         if (((providers == null) || (providers.Count == 0)) && ((cmdlets == null) || (cmdlets.Count == 0)))
         {
             try
             {
                 if (type != null)
                 {
                     ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes);
                     if (constructor != null)
                     {
                         constructor.Invoke(null);
                     }
                 }
                 if (type2 != null)
                 {
                     ConstructorInfo info2 = type2.GetConstructor(Type.EmptyTypes);
                     if (info2 != null)
                     {
                         info2.Invoke(null);
                     }
                 }
             }
             catch (TargetInvocationException exception)
             {
                 throw exception.InnerException;
             }
         }
         if (cmdlets != null)
         {
             Dictionary <string, SessionStateCmdletEntry> dictionary3 = new Dictionary <string, SessionStateCmdletEntry>(cmdlets.Count, StringComparer.OrdinalIgnoreCase);
             foreach (KeyValuePair <string, SessionStateCmdletEntry> pair in cmdlets)
             {
                 dictionary3[pair.Key] = (SessionStateCmdletEntry)pair.Value.Clone();
             }
             _cmdletCache.Value[assembly] = dictionary3;
         }
         if (providers != null)
         {
             Dictionary <string, SessionStateProviderEntry> dictionary4 = new Dictionary <string, SessionStateProviderEntry>(providers.Count, StringComparer.OrdinalIgnoreCase);
             foreach (KeyValuePair <string, SessionStateProviderEntry> pair2 in providers)
             {
                 dictionary4[pair2.Key] = (SessionStateProviderEntry)pair2.Value.Clone();
             }
             _providerCache.Value[assembly] = providers;
         }
     }
 }