Windows PowerShell Sağlayıcısı Hızlı Başlangıcı

Bu konuda, yeni sürücü oluşturmanın temel işlevlerine sahip bir Windows PowerShell sağlayıcısının nasıl oluşturulacağı açıklanmaktadır. Sağlayıcılar hakkında genel bilgi için bkz. Windows PowerShell Sağlayıcısına Genel Bakış. Daha eksiksiz işlevselliğe sahip sağlayıcı örnekleri için bkz. Sağlayıcı Örnekleri.

Temel sağlayıcı yazma

Bir Windows PowerShell sağlayıcısının en temel işlevselliği sürücüleri oluşturmak ve kaldırmaktır. Bu örnekte, System.Management.Automation.Provider.DriveCmdletProvider sınıfının System.Management.Automation.Provider.DriveCmdletProvider.NewDrive* ve System.Management.Automation.Provider.DriveCmdletProvider* yöntemlerini uygulayacağız. Ayrıca bir sağlayıcı sınıfının nasıl bildirileceğini de göreceksiniz.

Sağlayıcı yazarken, sağlayıcı kullanılabilir olduğunda otomatik olarak oluşturulan varsayılan sürücüleri belirtebilirsiniz. Ayrıca bu sağlayıcıyı kullanan yeni sürücüler oluşturmak için bir yöntem de tanımlarsınız.

Bu konuda sağlanan örnekler, Access veritabanını Windows PowerShell sürücüsü olarak temsil eden daha büyük bir örneğin parçası olan AccessDBProviderSample02 örneğini temel alır.

Projeyi ayarlama

Visual Studio'da AccessDBProviderSample adlı bir Sınıf Kitaplığı projesi oluşturun. Projenizi Windows PowerShell'in başlatılacağı ve projenizi derleyip başlattığınızda sağlayıcının oturuma yüklenecek şekilde yapılandırmak için aşağıdaki adımları tamamlayın.

Sağlayıcı projesini yapılandırma
  1. System.Management.Automation derlemesini projenize başvuru olarak ekleyin.

  2. AccessDBProviderSample Özellikleri >> Hata Ayıklamaöğesine tıklayın. Projeyi başlatbölümünde, dış programı başlat tıklayın ve Windows PowerShell yürütülebilir dosyasına gidin (genellikle C:\Windows\System32\WindowsPowerShell\v1.0\.powershell.exe).

  3. Başlangıç Seçeneklerialtında, Komut satırı bağımsız değişkenleri kutusuna aşağıdakileri girin: -NoExit -Command "[Reflection.Assembly]::LoadFrom(AccessDBProviderSample.dll' ) | Import-Module"

Sağlayıcı sınıfını bildirme

Sağlayıcımız System.Management.Automation.Provider.DriveCmdletProvider sınıfından türetilir. Gerçek işlevsellik sağlayan sağlayıcıların çoğu (öğelere erişme ve bunları işleme, veri deposunda gezinme ve öğelerin içeriğini alma ve ayarlama) System.Management.Automation.Provider.NavigationCmdletProvider sınıfından türetilir.

Sınıfının System.Management.Automation.Provider.DriveCmdletProvidertüretildiğini belirtmeye ek olarak, bunu örnekte gösterildiği gibi System.Management.Automation.Provider.CmdletProviderAttribute ile süslemeniz gerekir.

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 Uygulama

System.Management.Automation.Provider.DriveCmdletProvider.NewDrive* yöntemi, bir kullanıcı sağlayıcınızın adını belirten Microsoft.PowerShell.Commands.NewPSDriveCommand cmdlet'ini çağırdığında Windows PowerShell altyapısı tarafından çağrılır. PSDriveInfo parametresi Windows PowerShell altyapısı tarafından geçirilir ve yöntemi yeni sürücüyü Windows PowerShell altyapısına döndürür. Bu yöntem yukarıda oluşturulan sınıfı içinde bildirilmelidir.

yöntemi önce hem sürücü nesnesinin hem de geçirilen sürücü kökünün mevcut olduğundan emin olup olmadığını denetler ve bunlardan biri yoksa null döndürür. Ardından, yeni bir sürücü ve sürücünün temsil ettiği Access veritabanına bağlantı oluşturmak için AccessDBPSDriveInfo iç sınıfının bir oluşturucusunu kullanır.

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;
    }

Aşağıda, yeni bir sürücü oluşturmak için kullanılan oluşturucuyu içeren AccessDBPSDriveInfo iç sınıfı ve sürücünün durum bilgilerini içerir.

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 Uygulama

System.Management.Automation.Provider.DriveCmdletProvider.RemoveDrive* yöntemi, bir kullanıcı Microsoft.PowerShell.Commands.RemovePSDriveCommand cmdlet'ini çağırdığında Windows PowerShell altyapısı tarafından çağrılır. Bu sağlayıcıdaki yöntemi Access veritabanı bağlantısını kapatır.

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;
    }