Criar um runspace com restrição

Por motivos de desempenho ou segurança, convém restringir os comandos do Windows PowerShell disponíveis para seu aplicativo host. Para fazer isso, crie um vazio System.Management.Automation.Runspaces.InitialSessionState chamando o método System.Management.Automation.Runspaces.InitialSessionState.Create* e adicione apenas os comandos que você deseja que disponíveis.

O uso de um runspace que carrega apenas os comandos especificados fornece um desempenho significativamente aprimorado.

Use os métodos da classe System.Management.Automation.Runspaces.SessionStateCmdletEntry para definir cmdlets para o estado inicial da sessão.

Você também pode tornar os comandos privados. Os comandos privados podem ser usados pelo aplicativo host, mas não pelos usuários do aplicativo.

Adicionando comandos a um runspace vazio

O exemplo a seguir demonstra como criar um InitialSessionState vazio e adicionar comandos a ele.

namespace Microsoft.Samples.PowerShell.Runspaces
{
  using System;
  using System.Collections.ObjectModel;
  using System.Management.Automation;
  using System.Management.Automation.Runspaces;
  using Microsoft.PowerShell.Commands;
  using PowerShell = System.Management.Automation.PowerShell;

  /// <summary>
  /// This class contains the Main entry point for the application.
  /// </summary>
  internal class Runspace10b
  {
    /// <summary>
    /// This sample shows how to create an empty initial session state,
    /// how to add commands to the session state, and then how to create a
    /// runspace that has only those two commands. A PowerShell object
    /// is used to run the Get-Command cmdlet to show that only two commands
    /// are available.
    /// </summary>
    /// <param name="args">Parameter not used.</param>
    private static void Main(string[] args)
    {
      // Create an empty InitialSessionState and then add two commands.
      InitialSessionState iss = InitialSessionState.Create();

      // Add the Get-Process and Get-Command cmdlets to the session state.
      SessionStateCmdletEntry ssce1 = new SessionStateCmdletEntry(
                                                            "Get-Process",
                                                            typeof(GetProcessCommand),
                                                            null);
      iss.Commands.Add(ssce1);

      SessionStateCmdletEntry ssce2 = new SessionStateCmdletEntry(
                                                            "Get-Command",
                                                            typeof(GetCommandCommand),
                                                            null);
      iss.Commands.Add(ssce2);

      // Create a runspace.
      using (Runspace myRunSpace = RunspaceFactory.CreateRunspace(iss))
      {
        myRunSpace.Open();
        using (PowerShell powershell = PowerShell.Create())
        {
          powershell.Runspace = myRunSpace;

          // Create a pipeline with the Get-Command command.
          powershell.AddCommand("Get-Command");

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

          Console.WriteLine("Verb                 Noun");
          Console.WriteLine("----------------------------");

          // Display each result object.
          foreach (PSObject result in results)
          {
            Console.WriteLine(
                             "{0,-20} {1}",
                             result.Members["verb"].Value,
                             result.Members["Noun"].Value);
          }
        }

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

      System.Console.WriteLine("Hit any key to exit...");
      System.Console.ReadKey();
    }
  }
}

Tornando os comandos privados

Você também pode tornar um comando privado, definindo-o como propriedade System.Management.Automation.CommandInfo.Visibility para System.Management.Automation.SessionStateEntryVisibilityPrivate. O aplicativo host e outros comandos podem chamar esse comando, mas o usuário do aplicativo não pode. No exemplo a seguir, o comando Get-ChildItem é privado.

defaultSessionState = InitialSessionState.CreateDefault();
commandIndex = GetIndexOfEntry(defaultSessionState.Commands, "Get-ChildItem");
defaultSessionState.Commands[commandIndex].Visibility = SessionStateEntryVisibility.Private;

this.runspace = RunspaceFactory.CreateRunspace(defaultSessionState);
this.runspace.Open();

Consulte Também

criando um InitialSessionState