Windows PowerShell 提供程序快速入门

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

编写基本提供程序

Windows PowerShell提供程序的最基本功能是创建和删除驱动器。 本示例实现System.Management.Automation.Provider.Drivecmdletprovider.Newdrive 和System.Management.Automation.Provider.Drivecmdletprovider.Removedrive* 方法。 还将了解如何声明提供程序类。

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

本主题中提供的示例基于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;
    }