functions/Install-DotNetTool.ps1

# <copyright file="Install-DotNetTool.ps1" company="Endjin Limited">
# Copyright (c) Endjin Limited. All rights reserved.
# </copyright>

<#
.SYNOPSIS
    Simple wrapper to install a .Net global tool if it is not already installed.
.DESCRIPTION
    Simple wrapper to install a .Net Global Tool if it is not already installed. Whilst a version can be specified, this will not
    be honoured in the scenario where a different version of the tool is already installed.
.EXAMPLE
    PS C:\> <example usage>
    Explanation of what the example does
.PARAMETER Name
    The name of the .Net global tool to install
.PARAMETER Version
    The version of the global tool to install. NOTE: If the global tool is already installed this version will not be honoured.
.PARAMETER Global
    When true (the default), the tool is installed for the current user.
#>

function Install-DotNetTool
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string] $Name,

        [Parameter()]
        [Version] $Version,
        
        [Parameter()]
        [bool] $Global = $true
    )

    $existingTools = & dotnet tool list -g
    
    if ( !($existingTools | select-string $Name) ) {
        & dotnet tool install -g $Name --version "$Version"
    }

    # Ensure .NET global tools are available in the PATH environment variable
    if ($IsWindows) {
        $toolsPath = Join-Path $env:USERPROFILE ".dotnet/tools"
    }
    else {
        $toolsPath = Join-Path $env:HOME ".dotnet/tools"
    }
    if ($toolsPath -notin ($env:PATH -split [IO.Path]::PathSeparator)) {
        $env:PATH = "{0}{1}{2}" -f $env:PATH, [IO.Path]::PathSeparator, $toolsPath
    }
}