共用方式為


教學課程:使用 .NET CLI 安裝和使用 .NET 全域工具

本文適用於: ✔️.NET Core 2.1 SDK 和更新版本

本教學課程教您如何安裝和使用全域工具。 您可以使用 在本系列第一個教學課程中建立的工具。

先決條件

從 .NET 10.0.100 開始,您可以使用 dnx 執行 .NET 工具,而不需要永久安裝:

  1. 直接使用 dnx (簡化語法) 執行工具:

    dnx microsoft.botsay --add-source ./nupkg microsoft.botsay hello from the bot
    

    --add-source 參數會告訴 .NET CLI,在 NuGet.org 上無法使用工具時,使用 ./nupkg 目錄作為 NuGet 套件的其他來源。

將工具用作全域工具(傳統安裝)

如果您喜歡永久安裝以頻繁使用:

  1. microsoft.botsay 專案資料夾中執行 dotnet tool install 命令,從套件安裝工具:

    dotnet tool install --global --add-source ./nupkg microsoft.botsay
    

    --global 參數會告知 .NET CLI 將工具二進位檔安裝在自動新增至 PATH 環境變數的預設位置。

    --add-source 參數會告知 .NET CLI 暫時使用 ./nupkg 目錄作為 NuGet 套件的額外來源。 您為套件指定了唯一的名稱,以確保它只能在 ./nupkg 目錄中找到,而不是在 Nuget.org 網站上找到。

    輸出顯示用於呼叫工具的命令和安裝的版本:

    You can invoke the tool using the following command: botsay
    Tool 'microsoft.botsay' (version '1.0.0') was successfully installed.
    

    備註

    根據預設,要安裝的 .NET 二進位檔架構代表目前執行的 OS 架構。 若要指定不同的 OS 架構,請參閱 dotnet tool install, --arch option

  2. 叫用工具:

    botsay hello from the bot
    

    備註

    如果此指令失敗,您可能需要開啟新的終端機來重新整理 PATH。

  3. 執行 dotnet tool uninstall 命令來移除工具:

    dotnet tool uninstall -g microsoft.botsay
    

將工具用作安裝在自訂位置的全域工具

  1. 從套件中安裝工具。

    在 Windows 上:

    dotnet tool install --tool-path c:\dotnet-tools --add-source ./nupkg microsoft.botsay
    

    在 Linux 或 macOS 上:

    dotnet tool install --tool-path ~/bin --add-source ./nupkg microsoft.botsay
    

    參數 --tool-path 會告知 .NET CLI 在指定位置安裝工具二進位檔。 如果目錄不存在,則會建立它。 此目錄不會自動新增至 PATH 環境變數。

    輸出顯示用於呼叫工具的命令和安裝的版本:

    You can invoke the tool using the following command: botsay
    Tool 'microsoft.botsay' (version '1.0.0') was successfully installed.
    
  2. 叫用工具:

    在 Windows 上:

    c:\dotnet-tools\botsay hello from the bot
    

    在 Linux 或 macOS 上:

    ~/bin/botsay hello from the bot
    
  3. 執行 dotnet tool uninstall 命令來移除工具:

    在 Windows 上:

    dotnet tool uninstall --tool-path c:\dotnet-tools microsoft.botsay
    

    在 Linux 或 macOS 上:

    dotnet tool uninstall --tool-path ~/bin microsoft.botsay
    

疑難排解

如果您在遵循教學課程時收到錯誤訊息,請參閱 針對 .NET 工具使用問題進行疑難排解

後續步驟

在本教學課程中,您已安裝並使用工具作為全域工具。 如需如何安裝及使用廣域工具的相關資訊,請參閱 管理廣域工具。 若要安裝和使用與本機工具相同的工具,請繼續進行下一個教學課程。