Windows PowerShell 提供程序快速入门

本主题介绍如何创建具有创建新驱动器的基本功能的 Windows PowerShell 提供程序。 有关提供程序的一般信息,请参阅 Windows PowerShell 提供程序概述。 有关具有更完整功能的提供程序示例,请参阅 提供程序示例

编写基本提供程序

Windows PowerShell 提供程序的最基本功能是创建和删除驱动器。 在此示例中,我们实现 System.Management.Automation.Provider.DriveCmdletProvider.NewDrive*System.Management.Automation.Provider.DriveCmdletProvider.RemoveDrive*System.Management.Automation.Provider.DriveCmdletProvider 类的方法。 你还将了解如何声明提供程序类。

编写提供程序时,可以指定在提供程序可用时自动创建的默认驱动器驱动器。 此外,还可以定义一个方法来创建使用该提供程序的新驱动器。

本主题中提供的示例基于 AccessDBProviderSample02 示例,该示例是将 Access 数据库表示为 Windows PowerShell 驱动器的大型示例的一部分。

设置项目

在 Visual Studio 中,创建名为 AccessDBProviderSample 的类库项目。 完成以下步骤以配置项目,以便在生成和启动项目时启动 Windows PowerShell,并将提供程序加载到会话中。

配置提供程序项目
  1. 将 System.Management.Automation 程序集添加为对项目的引用。

  2. 单击 Project > AccessDBProviderSample 属性 > 调试。 在 启动项目中,单击 启动外部程序,然后导航到 Windows PowerShell 可执行文件(通常 C:\Windows\System32\WindowsPowerShell\v1.0\.powershell.exe)。

  3. “开始选项”下,在 命令行参数 框中输入以下内容:-NoExit -Command "[Reflection.Assembly]::LoadFrom(AccessDBProviderSample.dll' ) | Import-Module"

声明提供程序类

我们的提供程序派生自 System.Management.Automation.Provider.DriveCmdletProvider 类。 提供真实功能的大多数提供程序(访问和作项、导航数据存储和获取和设置项内容)派生自 System.Management.Automation.Provider.NavigationCmdletProvider 类。

除了指定类派生自 System.Management.Automation.Provider.DriveCmdletProvider之外,还必须使用 System.Management.Automation.Provider.CmdletProviderAttribute 对其进行修饰,如示例中所示。

namespace Microsoft.Samples.PowerShell.Providers
{
  using System;
  using System.Data;
  using System.Data.Odbc;
  using System.IO;
  using System.Management.Automation;
  using System.Management.Automation.Provider;

  #region AccessDBProvider

  [CmdletProvider("AccessDB", ProviderCapabilities.None)]
  public class AccessDBProvider : DriveCmdletProvider
  {

}
}

实现 NewDrive

当用户调用指定提供程序名称的 Microsoft.PowerShell.Commands.NewPSDriveCommand cmdlet 时,Windows PowerShell 引擎将调用 System.Management.Automation.Provider.DriveCmdletProvider.NewDrive* 方法。 PSDriveInfo 参数由 Windows PowerShell 引擎传递,该方法将新驱动器返回到 Windows PowerShell 引擎。 必须在上面创建的类中声明此方法。

该方法首先检查以确保传入的驱动器对象和驱动器根都存在,如果其中任一项不存在,则返回 null。 然后,它使用内部类 AccessDBPSDriveInfo 的构造函数创建新驱动器,并连接到驱动器所表示的 Access 数据库。

protected override PSDriveInfo NewDrive(PSDriveInfo drive)
    {
      // Check if the drive object is null.
      if (drive == null)
      {
        WriteError(new ErrorRecord(
                   new ArgumentNullException("drive"),
                   "NullDrive",
                   ErrorCategory.InvalidArgument,
                   null));

        return null;
      }

      // Check if the drive root is not null or empty
      // and if it is an existing file.
      if (String.IsNullOrEmpty(drive.Root) || (File.Exists(drive.Root) == false))
      {
        WriteError(new ErrorRecord(
                   new ArgumentException("drive.Root"),
                   "NoRoot",
                   ErrorCategory.InvalidArgument,
                   drive));

        return null;
      }

      // Create a new drive and create an ODBC connection to the new drive.
      AccessDBPSDriveInfo accessDBPSDriveInfo = new AccessDBPSDriveInfo(drive);
      OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder();

      builder.Driver = "Microsoft Access Driver (*.mdb)";
      builder.Add("DBQ", drive.Root);

      OdbcConnection conn = new OdbcConnection(builder.ConnectionString);
      conn.Open();
      accessDBPSDriveInfo.Connection = conn;

      return accessDBPSDriveInfo;
    }

下面是 AccessDBPSDriveInfo 内部类,其中包括用于创建新驱动器的构造函数,并包含驱动器的状态信息。

internal class AccessDBPSDriveInfo : PSDriveInfo
  {
    /// <summary>
    /// A reference to the connection to the database.
    /// </summary>
    private OdbcConnection connection;

    /// <summary>
    /// Initializes a new instance of the AccessDBPSDriveInfo class.
    /// The constructor takes a single argument.
    /// </summary>
    /// <param name="driveInfo">Drive defined by this provider</param>
    public AccessDBPSDriveInfo(PSDriveInfo driveInfo)
           : base(driveInfo)
    {
    }

    /// <summary>
    /// Gets or sets the ODBC connection information.
    /// </summary>
    public OdbcConnection Connection
    {
        get { return this.connection; }
        set { this.connection = value; }
    }
  }

实现 RemoveDrive

当用户调用 Microsoft.PowerShell.Commands.RemovePSDriveCommand cmdlet 时,Windows PowerShell 引擎将调用 System.Management.Automation.Provider.DriveCmdletProvider.RemoveDrive* 方法。 此提供程序中的方法将关闭与 Access 数据库的连接。

protected override PSDriveInfo RemoveDrive(PSDriveInfo drive)
    {
      // Check if drive object is null.
      if (drive == null)
      {
        WriteError(new ErrorRecord(
                   new ArgumentNullException("drive"),
                   "NullDrive",
                   ErrorCategory.InvalidArgument,
                   drive));

        return null;
      }

      // Close the ODBC connection to the drive.
      AccessDBPSDriveInfo accessDBPSDriveInfo = drive as AccessDBPSDriveInfo;

      if (accessDBPSDriveInfo == null)
      {
         return null;
      }

      accessDBPSDriveInfo.Connection.Close();

      return accessDBPSDriveInfo;
    }