共用方式為


如何建立命令行預測器

PSReadLine 2.1.0 藉由實作預測性 IntelliSense 功能引進智慧命令行預測器的概念。 PSReadLine 2.2.2 透過新增外掛程式模型來擴充該功能,讓您建立自己的命令行預測器。

預測性 IntelliSense 會在您輸入時提供建議,藉此增強索引標籤完成。 預測建議會顯示為游標後面的彩色文字。 這可讓您根據命令歷程記錄或其他網域特定外掛程式的比對預測,探索、編輯和執行完整命令。

系統需求

若要建立及使用外掛程式預測器,您必須使用下列版本的軟體:

  • PowerShell 7.2 (或更新版本) - 提供建立命令預測器所需的 API
  • PSReadLine 2.2.2 (或更新版本) - 可讓您設定 PSReadLine 使用外掛程式

預測器概觀

預測器是PowerShell二進位模組。 模組必須實作 System.Management.Automation.Subsystem.Prediction.ICommandPredictor 介面。 這個介面會宣告用來查詢預測結果的方法,並提供意見反應。

當卸除時,預測器模組必須 CommandPredictor 向PowerShell的 SubsystemManager 註冊子系統,並在卸除時取消註冊本身。

下圖顯示PowerShell中預測值的架構。

架構

建立程序代碼

若要建立預測值,您必須為平臺安裝 .NET 6 SDK。 如需 SDK 的詳細資訊,請參閱 下載 .NET 6.0

依照下列步驟建立新的PowerShell模組專案:

  1. dotnet使用命令行工具來建立 starter classlib 專案。

    dotnet new classlib --name SamplePredictor
    
  2. SamplePredictor.csproj編輯 以包含下列資訊:

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="Microsoft.PowerShell.SDK" Version="7.2.0" />
      </ItemGroup>
    
    </Project>
    
  3. 刪除 所dotnet建立的預設Class1.cs檔案,並將下列程式代碼SamplePredictorClass.cs複製到專案資料夾中的檔案。

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

    下列範例程式代碼會針對所有使用者輸入的預測結果傳回字串 「HELLO WORLD」。 由於範例預測值不會處理任何意見反應,因此程式代碼不會從 介面實作意見反應方法。 變更預測和意見反應程序代碼,以符合預測工具的需求。

    注意

    PSReadLine 的清單檢視不支援多行建議。 每個建議都應該是單行。 如果您的程式代碼有多行建議,您應該將這幾行分割成個別的建議,或將行聯結為分號 (;)。

  4. 執行 dotnet build 以產生元件。 您可以在項目資料夾的位置中找到 bin/Debug/net6.0 已編譯的元件。

    注意

    為了確保回應式用戶體驗,ICommandPredictor 介面有 20 毫秒的逾時回應預測器。 您的預測程式代碼必須傳回小於 20 毫秒的結果才能顯示。

使用預測工具外掛程式

若要試用新的預測值,請開啟新的 PowerShell 7.2 工作階段,然後執行下列命令:

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

在工作階段中載入元件時,您會在終端機中輸入時看到 「HELLO WORLD」 文字。 您可以按 F2 在檢視和List檢視之間Inline切換。

如需 PSReadLine 選項的詳細資訊,請參閱 Set-PSReadLineOption

您可以使用下列命令來取得已安裝預測器的清單:

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

注意

Get-PSSubsystem 是 PowerShell 7.1 中引進的實驗性 Cmdlet,您必須啟用 PSSubsystemPluginModel 實驗性功能才能使用此 Cmdlet。 如需詳細資訊,請參閱 使用實驗性功能