Exemplo n.º 1
0
        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();
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Verifies if the InitialSessionState of the current process.
        /// </summary>
        /// <returns></returns>
        private static bool DoesCurrentRunspaceIncludeCoreHelpCmdlet()
        {
            InitialSessionState iss =
                System.Management.Automation.Runspaces.Runspace.DefaultRunspace.InitialSessionState;

            if (iss != null)
            {
                IEnumerable <SessionStateCommandEntry> publicGetHelpEntries = iss
                                                                              .Commands["Get-Help"]
                                                                              .Where(entry => entry.Visibility == SessionStateEntryVisibility.Public);
                if (publicGetHelpEntries.Count() != 1)
                {
                    return(false);
                }

                foreach (SessionStateCommandEntry getHelpEntry in publicGetHelpEntries)
                {
                    SessionStateCmdletEntry getHelpCmdlet = getHelpEntry as SessionStateCmdletEntry;
                    if ((getHelpCmdlet != null) && (getHelpCmdlet.ImplementingType.Equals(typeof(GetHelpCommand))))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Exemplo n.º 3
0
        public override InitialSessionStateEntry Clone()
        {
            SessionStateCmdletEntry stateCmdletEntry = new SessionStateCmdletEntry(this.Name, this._implementingType, this._helpFileName, this.Visibility);

            stateCmdletEntry.SetPSSnapIn(this.PSSnapIn);
            stateCmdletEntry.SetModule(this.Module);
            return((InitialSessionStateEntry)stateCmdletEntry);
        }
Exemplo n.º 4
0
 internal void AddSessionStateCmdletEntryToCache(SessionStateCmdletEntry entry)
 {
     if (this.IsSpecialCmdlet(entry.ImplementingType))
     {
         return;
     }
     this.AddCmdletInfoToCache(this.NewCmdletInfo(entry));
 }
Exemplo n.º 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-SPOnline", typeof(ConnectSPOnline), 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-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("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();
            }
        }
Exemplo n.º 6
0
        internal static CmdletInfo NewCmdletInfo(
            SessionStateCmdletEntry entry,
            ExecutionContext context)
        {
            CmdletInfo cmdletInfo = new CmdletInfo(entry.Name, entry.ImplementingType, entry.HelpFileName, entry.PSSnapIn, context);

            cmdletInfo.Visibility = entry.Visibility;
            cmdletInfo.SetModule(entry.Module);
            return(cmdletInfo);
        }
Exemplo n.º 7
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();
        }
Exemplo n.º 8
0
        public PsRunspace()
        {
            var config = InitialSessionState.CreateDefault();
            SessionStateCmdletEntry requireModule = new SessionStateCmdletEntry(
                "Require-Module", typeof(RequireCommand), "");

            var requireAlias = new SessionStateAliasEntry("Require", "Require-Module");

            config.Commands.Add(requireModule);
            config.Commands.Add(requireAlias);

            PsHost = new CustomPsHost();

            Runspace = RunspaceFactory.CreateRunspace(PsHost, config);
            Runspace.DefaultRunspace = Runspace;
            Runspace.Open();
        }
        /// <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();
        }
Exemplo n.º 10
0
        public PSTestScope(bool connect = true)
        {
            configuration = new Configuration();

            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();


            if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var executionPolicyPipeline = _runSpace.CreatePipeline();

                // This is only works / is needed on Windows
                var executionPolicyCmd = new Command("Set-ExecutionPolicy");
                executionPolicyCmd.Parameters.Add("ExecutionPolicy", "Unrestricted");
                executionPolicyPipeline.Commands.Add(executionPolicyCmd);
                executionPolicyPipeline.Invoke();
            }

            var pipeLine = _runSpace.CreatePipeline();

            if (connect)
            {
                var cmd = new Command("Connect-PnPOnline");
                cmd.Parameters.Add("Url", configuration.SiteUrl);
                // Use the configured Credential Manager to authenticate
                cmd.Parameters.Add("Credentials", configuration.Credentials);
                pipeLine.Commands.Add(cmd);
                pipeLine.Invoke();
            }
        }
Exemplo n.º 11
0
 private bool DoesInitialSessionStateIncludeGetCommandWithListImportedSwitch()
 {
     if (!this._initialSessionStateIncludesGetCommandWithListImportedSwitch.HasValue)
     {
         lock (this._initialSessionStateIncludesGetCommandWithListImportedSwitchLock)
         {
             if (!this._initialSessionStateIncludesGetCommandWithListImportedSwitch.HasValue)
             {
                 bool flag = false;
                 InitialSessionState initialSessionState = this.RunspacePool.InitialSessionState;
                 if (initialSessionState != null)
                 {
                     IEnumerable <SessionStateCommandEntry> source = from entry in initialSessionState.Commands["Get-Command"]
                                                                     where entry.Visibility == SessionStateEntryVisibility.Public
                                                                     select entry;
                     SessionStateFunctionEntry e = source.OfType <SessionStateFunctionEntry>().FirstOrDefault <SessionStateFunctionEntry>();
                     if (e != null)
                     {
                         if (e.ScriptBlock.ParameterMetadata.BindableParameters.ContainsKey("ListImported"))
                         {
                             flag = true;
                         }
                     }
                     else
                     {
                         SessionStateCmdletEntry entry2 = source.OfType <SessionStateCmdletEntry>().FirstOrDefault <SessionStateCmdletEntry>();
                         if ((entry2 != null) && entry2.ImplementingType.Equals(typeof(GetCommandCommand)))
                         {
                             flag = true;
                         }
                     }
                 }
                 this._initialSessionStateIncludesGetCommandWithListImportedSwitch = new bool?(flag);
             }
         }
     }
     return(this._initialSessionStateIncludesGetCommandWithListImportedSwitch.Value);
 }
Exemplo n.º 12
0
        private static bool DoesCurrentRunspaceIncludeCoreHelpCmdlet()
        {
            InitialSessionState initialSessionState = Runspace.DefaultRunspace.InitialSessionState;

            if (initialSessionState != null)
            {
                IEnumerable <SessionStateCommandEntry> source = from entry in initialSessionState.Commands["Get-Help"]
                                                                where entry.Visibility == SessionStateEntryVisibility.Public
                                                                select entry;
                if (source.Count <SessionStateCommandEntry>() != 1)
                {
                    return(false);
                }
                foreach (SessionStateCommandEntry entry in source)
                {
                    SessionStateCmdletEntry entry2 = entry as SessionStateCmdletEntry;
                    if ((entry2 != null) && entry2.ImplementingType.Equals(typeof(GetHelpCommand)))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemplo n.º 13
0
        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)
                {
                    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);
        }
Exemplo n.º 14
0
 private CmdletInfo NewCmdletInfo(SessionStateCmdletEntry entry) => CommandDiscovery.NewCmdletInfo(entry, this._context);
Exemplo n.º 15
0
 public void InitialPlugin(IServiceProvider serviceProvider)
 {
     PowerShellRecourseLoader = new PowerShellRecourseLoader(serviceProvider);
     SessionStateCmdletEntry cmdletEntry = new SessionStateCmdletEntry("get-proc", typeof(AddDnsCacheItem), null);
 }
Exemplo n.º 16
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);
 }
Exemplo n.º 17
0
        public static void InitializeRunspaceConfiguration(InitialSessionState config)
        {
            config.LanguageMode = PSLanguageMode.FullLanguage;
            config.UseFullLanguageModeInDebugger = true;

            var cmdlets = new List <SessionStateCmdletEntry>();

            AddCmdletConfigurationEntries(new List <Type>()
            {
                //Common
                typeof(ConvertSCPathCmdlet),
                typeof(InvokeGenericMethodCmdlet),

                //Book
                typeof(WriteTextCmdlet),
                typeof(WriteHtmlCmdlet),
                typeof(WriteImageCmdlet),
                typeof(WriteContentCmdlet),
                typeof(WriteLatexCmdlet),
                typeof(AddBookCharacterStyleCmdlet),
                typeof(AddBookParagraphStyleCmdlet),
                typeof(SetBookDefaultCharacterPropertiesCmdlet),
                typeof(SetBookDefaultParagraphPropertiesCmdlet),
                typeof(SetBookDefaultPropertiesCmdlet),
                typeof(AddBookPageBreakCmdlet),
                typeof(AddBookSectionCmdlet),
                typeof(SetBookSectionCmdlet),
                typeof(SetBookSectionHeaderCmdlet),
                typeof(SetBookSectionFooterCmdlet),
                typeof(AddBookTocCmdlet),
                typeof(AddBookShapeCmdlet),
                typeof(NewBookCmdlet),
                typeof(MergeBookCmdlet),
                typeof(SaveBookCmdlet),
                typeof(WriteSpreadTableCmdlet),
                typeof(WriteDataTableCmdlet),
                //typeof(OutBookTemplateCmdlet),
                typeof(WriteSyntaxTextCmdlet),
                typeof(WriteErrorMessageCmdlet),
                typeof(WriteMarkdownCmdlet),
                typeof(ClearBookCmdlet),

                //Spreadsheet
                typeof(OutSpreadTableCmdlet),
                typeof(NewSpreadPivotCmdlet),
                typeof(NewSimpleSpreadChartCmdlet),
                typeof(NewSpreadChartCmdlet),
                typeof(NewSpreadsheetCmdlet),
                typeof(SaveSpreadsheetCmdlet),
                typeof(MergeSpreadsheetCmdlet),
                typeof(OutSpreadTemplateCmdlet),
                typeof(GetSpreadTableCmdlet),
                typeof(SaveSpreadChartCmdlet),
                typeof(ClearSpreadsheetCmdlet),
                typeof(GetSpreadTableNamesCmdlet),
                typeof(GetSpreadSheetNamesCmdlet),
                typeof(SelectSpreadSheetCmdlet),

                //Chart
                typeof(NewChartCmdlet),
                typeof(AddChartSeriesCmdlet),
                typeof(AddChartTitleCmdlet),
                typeof(AddChartPaneCmdlet),
                typeof(SetChartLegendCmdlet),
                typeof(AddChartLegendCmdlet),
                typeof(SetChartSeriesLabelCmdlet),
                typeof(SetChartTotalLabelCmdlet),
                typeof(WriteChartCmdlet),
                typeof(AddChartAxisCmdlet),
                typeof(SetChartAxisCmdlet),
                typeof(SetChartDefaultPaneCmdlet),
                typeof(SetChartAxisLabelCmdlet),
                typeof(SetChartAxisTitleCmdlet),
                typeof(AddChartAxisCustomLabelCmdlet),
                typeof(AddChartConstantLineCmdlet),
                typeof(AddChartIndicatorCmdlet),
                typeof(AddChartScaleBreakCmdlet),
                typeof(AddChartSeriesTitleCmdlet),
                typeof(AddChartAnnotationCmdlet),
                typeof(AddChartSeriesColorizerCmdlet),
                typeof(AddChartSegmentColorizerCmdlet),
                typeof(SaveChartCmdlet),
                typeof(SaveChartTemplateCmdlet),

                //Sankey
                typeof(WriteSankeyDiagramCmdlet),
                typeof(SaveSankeyDiagramCmdlet),

                //Grid
                typeof(OutDataCmdlet),
                typeof(OutDataSetCmdlet),
                typeof(RemoveDataTableCmdlet),
                typeof(ClearDataCmdlet),
                typeof(SelectDataTableCmdlet),

                //Map
                typeof(NewMapCmdlet),
                typeof(WriteMapCmdlet),
                typeof(AddMapLayerVectorFileCmdlet),
                typeof(AddMapLayerSqlCmdlet),
                typeof(AddMapLayerWktCmdlet),
                typeof(AddMapLayerImageCmdlet),
                typeof(AddMapLayerVectorDataCmdlet),
                typeof(AddMapLayerVectorItemsCmdlet),
                typeof(AddMapItemCmdlet),
                typeof(AddMapChoroplethColorizerCmdlet),
                typeof(AddMapGraphColorizerCmdlet),
                typeof(AddMapKeyColorizerCmdlet),
                typeof(AddMapLegendCmdlet),
                typeof(AddMapLayerSearchCmdlet),
                typeof(AddMapLayerRouteCmdlet),
                typeof(AddMapOverlayCmdlet),
                typeof(AddMapMiniMapCmdlet),
                typeof(AddMapClustererCmdlet),
                typeof(SaveMapCmdlet),

                //Heap
                typeof(OutFileViewerCmdlet),

                //Script
                typeof(InvokeSCScriptCmdlet),
                typeof(GetDbConnectionCmdlet),
                typeof(SetDbConnectionCmdlet),
                typeof(InvokeSqlScriptCmdlet),
                typeof(InvokeSqlQueryCmdlet),
                typeof(ExportTableToDatabaseCmdlet),
                typeof(GetSCHostCmdlet),
                typeof(ConvertToObjectListCmdlet),
                typeof(ConvertToVectorCmdlet),
                typeof(ConvertToPivotCmdlet),
                typeof(ConvertToUnPivotCmdlet),

                //ImportExport
                typeof(ImportDelimitedTextCmdlet),
                typeof(ImportFixedLengthTextCmdlet),
                typeof(ExportDelimitedTextCmdlet),
                typeof(ExportFixedLengthTextCmdlet),
                typeof(ImportDbfCmdlet),
                typeof(ExportDbfCmdlet),

                //Async
                typeof(InvokeAsyncCommandsCmdlet),
                typeof(NewSCRunspaceCmdlet),
                typeof(NewSCRunspacePoolCmdlet)

#if DEBUG
                , typeof(TestCmdlet)
#endif
            });

            config.Commands.Add(cmdlets);


            void AddCmdletConfigurationEntries(IEnumerable <Type> types)
            {
                foreach (var type in types)
                {
                    AddCmdletConfigurationEntry(type);
                }
            }

            void AddCmdletConfigurationEntry(Type cmdletType)
            {
                var attrsCmdlet = cmdletType.GetCustomAttributes(typeof(CmdletAttribute), true);

                if (attrsCmdlet == null || attrsCmdlet.Length <= 0)
                {
                    throw new Exception($"Cannot register cmdlet: {cmdletType.Name}");
                }

                var attrCmdlet = ((CmdletAttribute)attrsCmdlet[0]);
                var cmdletName = $"{attrCmdlet.VerbName}-{attrCmdlet.NounName}";

                var cmdletEntry = new SessionStateCmdletEntry(cmdletName, cmdletType, null);

                cmdlets.Add(cmdletEntry);
            }
        }
Exemplo n.º 18
0
 /// <summary>
 /// Add an new SessionState cmdlet entry to this session state object...
 /// </summary>
 /// <param name="entry">The entry to add</param>
 /// <param name="local">If local, add cmdlet to current scope. Else, add to module scope</param>
 internal void AddSessionStateEntry(SessionStateCmdletEntry entry, bool local)
 {
     ExecutionContext.CommandDiscovery.AddSessionStateCmdletEntryToCache(entry, local);
 }
Exemplo n.º 19
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();
        }