当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 创建初始会话状态

作者:精品下载站 日期:2024-12-14 02:46:27 浏览:12 分类:玩电脑

创建初始会话状态


PowerShell 命令在运行空间中运行。要在应用程序中托管 PowerShell,您必须创建 System.Management.Automation.Runspaces.Runspace 对象。每个运行空间都有一个与其关联的 System.Management.Automation.Runspaces.InitialSessionState 对象。 InitialSessionState 指定运行空间的特征,例如哪些命令、变量和模块可用于该运行空间。

创建默认的InitialSessionState

InitialSessionState 类的 CreateDefault 和 CreateDefault2 方法可用于创建 InitialSessionState 对象。 CreateDefault 方法创建一个 InitialSessionState,其中加载了所有内置命令,而 CreateDefault2 方法仅加载托管 PowerShell 所需的命令(来自 Microsoft.PowerShell.Core 模块的命令)。

如果您想进一步限制主机应用程序中可用的命令,您需要创建一个受限的运行空间。有关信息,请参阅创建受限运行空间。

以下代码演示如何创建 InitialSessionState、将其分配给运行空间、向该运行空间中的管道添加命令以及调用命令。有关添加和调用命令的更多信息,请参阅添加和调用命令。

namespace SampleHost
{
  using System;
  using System.Management.Automation;
  using System.Management.Automation.Runspaces;

  class HostP4b
  {
    static void Main(string[] args)
    {
      // Call InitialSessionState.CreateDefault() to create an empty 
      // InitialSessionState object, then add the variables that will be 
      // available when the runspace is opened.
      InitialSessionState iss = InitialSessionState.CreateDefault();
      SessionStateVariableEntry var1 = 
        new SessionStateVariableEntry("test1",
                                      "MyVar1",
                                      "Initial session state MyVar1 test");
      iss.Variables.Add(var1);

      SessionStateVariableEntry var2 = 
        new SessionStateVariableEntry("test2",
                                      "MyVar2",
                                      "Initial session state MyVar2 test");
      iss.Variables.Add(var2);

      // Call RunspaceFactory.CreateRunspace(InitialSessionState) to 
      // create the runspace where the pipeline is run.
      Runspace rs = RunspaceFactory.CreateRunspace(iss);
      rs.Open();

      // Call PowerShell.Create() to create the PowerShell object, then 
      // specify the runspace and pipeline commands.
      PowerShell ps = PowerShell.Create();
      ps.Runspace = rs;
      ps.AddCommand("Get-Variable");
      ps.AddArgument("test*");

      Console.WriteLine("Variable             Value");
      Console.WriteLine("--------------------------");

      // Call ps.Invoke() to run the pipeline synchronously.
      foreach (PSObject result in ps.Invoke())
      {
        Console.WriteLine("{0,-20}{1}",
            result.Members["Name"].Value,
            result.Members["Value"].Value);
      } // End foreach.

      // Close the runspace to free resources.
      rs.Close();

    } // End Main.
  } // End SampleHost.
}

参见

创建受限运行空间

添加和调用命令

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯