Windows PowerShell プロバイダー クイック スタート

このトピックでは、新しいドライブを作成する基本的Windows PowerShellを持つプロバイダーを作成する方法について説明します。 プロバイダーに関する一般的な情報については、「プロバイダーの概要Windows PowerShellを参照してください。 より完全な機能を持つプロバイダーの例については、「プロバイダーのサンプル」 を参照してください

基本プロバイダーの作成

サービス プロバイダーの最も基本的なWindows PowerShellは、ドライブの作成と削除です。 この例では、System.Management.Automation.Provider.Drivecmdletprovider クラスの 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 の実装

System.Management.Automation.Provider.Drivecmdletprovider.Newdrive*メソッドは、ユーザーがプロバイダーの名前を指定してMicrosoft.PowerShell.Commands.NewPSDriveCommandコマンドレットを呼び出す際に、Windows PowerShell エンジンによって呼び出されます。 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 の実装

System.Management.Automation.Provider.Drivecmdletprovider.Removedrive*メソッドは、ユーザーがMicrosoft.PowerShell.Commands.RemovePSDriveCommandコマンドレットを呼び出す際に、Windows PowerShell エンジンによって呼び出されます。 このプロバイダーの メソッドは、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;
    }