Skip to content

Instantly share code, notes, and snippets.

@tmeckel
Created March 6, 2018 09:17
Show Gist options
  • Save tmeckel/13c026a4fe1705bfbf94bddd25780629 to your computer and use it in GitHub Desktop.
Save tmeckel/13c026a4fe1705bfbf94bddd25780629 to your computer and use it in GitHub Desktop.
Snippet, Powershell: Finding commands (executables)
$prgMap = @(
    @{
        "Name" = "gacutil.exe"
        "Type" = "Application"
        "DefaultPath" = $PSScriptRoot
        "VariableName" = "cmdGacutil"
    },
    @{
        "Name" = "appcmd.exe"
        "Type" = "Application"
        "DefaultPath" = Join-Path ([Environment]::SystemDirectory) "inetserv"
        "VariableName" = "cmdAppCmd"
    }
)

$prgMap | %{
    $prg = $_
    Write-Verbose ("Checking for [$($prg.Name)]")
    $type = $prg.Type
    if (-not $type) {
        $type = "Application"
    }

    $cmd = Get-Command -CommandType $type -Name $prg.Name -TotalCount 1 -ErrorAction:SilentlyContinue
    if (-not $cmd) {
        if ($prg.DefaultPath) {
            Write-Verbose ("$($prg.Name) not found in PATH. Trying default path [$($prg.DefaultPath)]")
            $cmd = Get-Command -CommandType $type -Name (Join-Path $prg.DefaultPath $prg.Name) -TotalCount 1 -ErrorAction:SilentlyContinue
        }
        if (-not $cmd) {
            Write-Error ("$($prg.Name) not found.") -ErrorAction:Stop
        }
    }
    if ($prg.VariableName) {
        New-Variable -Name $prg.VariableName -Value $cmd
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment