functions/Test-DotNetTool.ps1

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

<#
.SYNOPSIS
    Simple wrapper to check whether a given .NET tool is already installed.
.DESCRIPTION
    Simple wrapper to check whether a given .NET tool is already installed.
.EXAMPLE
    PS C:\> <example usage>
    Explanation of what the example does
.PARAMETER Name
    The name of the .NET tool to check
.PARAMETER Version
    The version of the .NET tool to check for. When unspecified any version found will cause this function to return true.
.PARAMETER Global
    When specified, the tool's installation status is checked in the global scope (i.e. for the current user).
.PARAMETER Local
    When specified, the tool's installation status is checked in the local scope (i.e. for the current project's .NET tool manifest).
.PARAMETER ToolPath
    When specified, the tool's installation status is checked in the specified directory.

#>

function Test-DotNetTool
{
    [CmdletBinding(DefaultParameterSetName="global")]
    param (
        [Parameter(Mandatory=$true)]
        [string] $Name,

        [Parameter()]
        [string] $Version,
        
        [Parameter(ParameterSetName="global")]
        [switch] $Global,

        [Parameter(ParameterSetName="local")]
        [switch] $Local,

        [Parameter(ParameterSetName="toolpath")]
        [string] $ToolPath
    )

    switch ($PSCmdlet.ParameterSetName) {
        "global" { $scopeArg = @("--global") }
        "local" { $scopeArg = @("--local") }
        "toolpath" { $scopeArg = @("--tool-path", $ToolPath) }
    }

    $allInstalledTools = & dotnet tool list @scopeArg
    $existingInstall = $allInstalledTools | select-string $Name

    if ($existingInstall -and $Version) {
        # parse out the currently installed version from the whitespace delimited columns
        $existingVersion = ($existingInstall.Line -split "[\s*]" | ? { $_ })[1]
        if ($existingVersion -ne $Version) {
            return $false
        }
    }
    elseif (!$existingInstall) {
        return $false
    }

    return $true    
}