Aracılığıyla paylaş


Komut satırı tahmincisi oluşturma

PSReadLine 2.1.0, Tahmine Dayalı IntelliSense özelliğini uygulayarak akıllı komut satırı tahmincisi kavramını ortaya çıkarmıştı. PSReadLine 2.2.2, kendi komut satırı tahminlerinizi oluşturmanıza olanak tanıyan bir eklenti modeli ekleyerek bu özellik üzerinde genişletilmiştir.

Tahmine dayalı IntelliSense, siz yazarken komut satırında öneriler sağlayarak sekme tamamlamayı geliştirir. Tahmin önerisi, imlecinizi izleyen renkli metin olarak görünür. Bu, komut geçmişinizden veya etki alanına özgü ek eklentilerden gelen eşleşen tahminlere göre tam komutları bulmanızı, düzenlemenizi ve yürütmenizi sağlar.

Sistem gereksinimleri

Eklenti tahmin aracı oluşturmak ve kullanmak için yazılımın aşağıdaki sürümlerini kullanıyor olmanız gerekir:

  • PowerShell 7.2 (veya üzeri) - komut tahmincisi oluşturmak için gereken API'leri sağlar
  • PSReadLine 2.2.2 (veya üzeri) - PSReadLine'ı eklentiyi kullanacak şekilde yapılandırmanıza olanak tanır

Tahmine genel bakış

Tahmin aracı bir PowerShell ikili modülüdür. Modülün arabirimini System.Management.Automation.Subsystem.Prediction.ICommandPredictor uygulaması gerekir. Bu arabirim, tahmin sonuçlarını sorgulamak ve geri bildirim sağlamak için kullanılan yöntemleri bildirir.

Bir tahmin modülünün yüklendiğinde PowerShell'lere SubsystemManager bir CommandPredictor alt sistem kaydetmesi ve kaldırıldığında kendi kaydını kaldırması gerekir.

Aşağıdaki diyagramda PowerShell'de bir tahmin aracının mimarisi gösterilmektedir.

Mimari

Kodu oluşturma

Tahmin aracı oluşturmak için platformunuz için .NET 6 SDK'sının yüklü olması gerekir. SDK hakkında daha fazla bilgi için bkz . .NET 6.0'ı indirme.

Aşağıdaki adımları izleyerek yeni bir PowerShell modülü projesi oluşturun:

  1. dotnet Başlangıç classlib projesi oluşturmak için komut satırı aracını kullanın.

    dotnet new classlib --name SamplePredictor
    
  2. SamplePredictor.csproj aşağıdaki bilgileri içerecek şekilde düzenleyin:

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="Microsoft.PowerShell.SDK" Version="7.2.0" />
      </ItemGroup>
    
    </Project>
    
  3. tarafından dotnet oluşturulan varsayılan Class1.cs dosyayı silin ve aşağıdaki kodu proje klasörünüzdeki bir SamplePredictorClass.cs dosyaya kopyalayın.

    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Management.Automation;
    using System.Management.Automation.Subsystem;
    using System.Management.Automation.Subsystem.Prediction;
    
    namespace PowerShell.Sample
    {
        public class SamplePredictor : ICommandPredictor
        {
            private readonly Guid _guid;
    
            internal SamplePredictor(string guid)
            {
                _guid = new Guid(guid);
            }
    
            /// <summary>
            /// Gets the unique identifier for a subsystem implementation.
            /// </summary>
            public Guid Id => _guid;
    
            /// <summary>
            /// Gets the name of a subsystem implementation.
            /// </summary>
            public string Name => "SamplePredictor";
    
            /// <summary>
            /// Gets the description of a subsystem implementation.
            /// </summary>
            public string Description => "A sample predictor";
    
            /// <summary>
            /// Get the predictive suggestions. It indicates the start of a suggestion rendering session.
            /// </summary>
            /// <param name="client">Represents the client that initiates the call.</param>
            /// <param name="context">The <see cref="PredictionContext"/> object to be used for prediction.</param>
            /// <param name="cancellationToken">The cancellation token to cancel the prediction.</param>
            /// <returns>An instance of <see cref="SuggestionPackage"/>.</returns>
            public SuggestionPackage GetSuggestion(PredictionClient client, PredictionContext context, CancellationToken cancellationToken)
            {
                string input = context.InputAst.Extent.Text;
                if (string.IsNullOrWhiteSpace(input))
                {
                    return default;
                }
    
                return new SuggestionPackage(new List<PredictiveSuggestion>{
                    new PredictiveSuggestion(string.Concat(input, " HELLO WORLD"))
                });
            }
    
            #region "interface methods for processing feedback"
    
            /// <summary>
            /// Gets a value indicating whether the predictor accepts a specific kind of feedback.
            /// </summary>
            /// <param name="client">Represents the client that initiates the call.</param>
            /// <param name="feedback">A specific type of feedback.</param>
            /// <returns>True or false, to indicate whether the specific feedback is accepted.</returns>
            public bool CanAcceptFeedback(PredictionClient client, PredictorFeedbackKind feedback) => false;
    
            /// <summary>
            /// One or more suggestions provided by the predictor were displayed to the user.
            /// </summary>
            /// <param name="client">Represents the client that initiates the call.</param>
            /// <param name="session">The mini-session where the displayed suggestions came from.</param>
            /// <param name="countOrIndex">
            /// When the value is greater than 0, it's the number of displayed suggestions from the list
            /// returned in <paramref name="session"/>, starting from the index 0. When the value is
            /// less than or equal to 0, it means a single suggestion from the list got displayed, and
            /// the index is the absolute value.
            /// </param>
            public void OnSuggestionDisplayed(PredictionClient client, uint session, int countOrIndex) { }
    
            /// <summary>
            /// The suggestion provided by the predictor was accepted.
            /// </summary>
            /// <param name="client">Represents the client that initiates the call.</param>
            /// <param name="session">Represents the mini-session where the accepted suggestion came from.</param>
            /// <param name="acceptedSuggestion">The accepted suggestion text.</param>
            public void OnSuggestionAccepted(PredictionClient client, uint session, string acceptedSuggestion) { }
    
            /// <summary>
            /// A command line was accepted to execute.
            /// The predictor can start processing early as needed with the latest history.
            /// </summary>
            /// <param name="client">Represents the client that initiates the call.</param>
            /// <param name="history">History command lines provided as references for prediction.</param>
            public void OnCommandLineAccepted(PredictionClient client, IReadOnlyList<string> history) { }
    
            /// <summary>
            /// A command line was done execution.
            /// </summary>
            /// <param name="client">Represents the client that initiates the call.</param>
            /// <param name="commandLine">The last accepted command line.</param>
            /// <param name="success">Shows whether the execution was successful.</param>
            public void OnCommandLineExecuted(PredictionClient client, string commandLine, bool success) { }
    
            #endregion;
        }
    
        /// <summary>
        /// Register the predictor on module loading and unregister it on module un-loading.
        /// </summary>
        public class Init : IModuleAssemblyInitializer, IModuleAssemblyCleanup
        {
            private const string Identifier = "843b51d0-55c8-4c1a-8116-f0728d419306";
    
            /// <summary>
            /// Gets called when assembly is loaded.
            /// </summary>
            public void OnImport()
            {
                var predictor = new SamplePredictor(Identifier);
                SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor, predictor);
            }
    
            /// <summary>
            /// Gets called when the binary module is unloaded.
            /// </summary>
            public void OnRemove(PSModuleInfo psModuleInfo)
            {
                SubsystemManager.UnregisterSubsystem(SubsystemKind.CommandPredictor, new Guid(Identifier));
            }
        }
    }
    

    Aşağıdaki örnek kod, tüm kullanıcı girişi için tahmin sonucu için "HELLO WORLD" dizesini döndürür. Örnek tahmin aracı hiçbir geri bildirimi işlemediğinden kod, arabirimden geri bildirim yöntemlerini uygulamaz. Tahmincinizin gereksinimlerini karşılamak için tahmin ve geri bildirim kodunu değiştirin.

    Not

    PSReadLine'ın liste görünümü çok satırlı önerileri desteklemez. Her öneri tek bir satır olmalıdır. Kodunuzun çok satırlı bir önerisi varsa, satırları ayrı önerilere bölmeniz veya satırları noktalı virgülle (; ) birleştirmeniz gerekir.

  4. Derlemeyi oluşturmak için komutunu çalıştırın dotnet build . Derlenmiş derlemeyi bin/Debug/net6.0 proje klasörünüzün konumunda bulabilirsiniz.

    Not

    Yanıt veren bir kullanıcı deneyimi sağlamak için ICommandPredictor arabiriminde Tahmincilerden gelen yanıtlar için 20ms zaman aşımı vardır. Tahmin kodunuz görüntülenecek 20 dakikadan kısa bir sürede sonuç döndürmelidir.

Predictor eklentinizi kullanma

Yeni tahmin aracınızı denemek için yeni bir PowerShell 7.2 oturumu açın ve aşağıdaki komutları çalıştırın:

Set-PSReadLineOption -PredictionSource HistoryAndPlugin
Import-Module .\bin\Debug\net6.0\SamplePredictor.dll

Derleme oturumda yüklendiğinde, terminale yazarken "HELLO WORLD" metnini görürsünüz. Görünüm ile görünüm arasında Inline geçiş yapmak için F2 tuşuna List basabilirsiniz.

PSReadLine seçenekleri hakkında daha fazla bilgi için bkz . Set-PSReadLineOption.

Aşağıdaki komutu kullanarak yüklü tahmincilerin listesini alabilirsiniz:

Get-PSSubsystem -Kind CommandPredictor
Kind              SubsystemType      IsRegistered Implementations
----              -------------      ------------ ---------------
CommandPredictor  ICommandPredictor          True {SamplePredictor}

Not

Get-PSSubsystem , PowerShell 7.1'de kullanıma sunulan deneysel bir cmdlet'tir Bu cmdlet'i kullanmak için deneysel özelliği etkinleştirmeniz PSSubsystemPluginModel gerekir. Daha fazla bilgi için bkz . Deneysel Özellikleri Kullanma.