教程:使用 .NET CLI 安装和使用 .NET 全局工具

本文适用于: ✔️.NET Core 2.1 SDK 及更高版本

本教程介绍如何安装和使用全局工具。 您使用的是在本系列的第一个教程中创建的工具。

先决条件

从 .NET 10.0.100 开始,可以使用以下方法运行 .NET 工具,而无需永久安装 dnx

  1. 使用 dnx 直接运行该工具(简化的语法):

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

    当该工具在 NuGet.org 上不可用时,该 --add-source 参数告知 .NET CLI 将 ./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 工具卸载 命令删除该工具:

    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 工具卸载 命令删除该工具:

    在 Windows 上:

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

    在 Linux 或 macOS 上:

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

故障排除

如果在遵循本教程时收到错误消息,请参阅 排查 .NET 工具使用问题

后续步骤

在本教程中,你已安装并使用工具作为全局工具。 有关如何安装和使用全局工具的详细信息,请参阅 管理全局工具。 若要安装和使用与本地工具相同的工具,请转到下一教程。