public/Get-BuildToolsPath.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

$buildToolsVersions = @{
    "15" = "15.0"
    "15.0" = "15.0"
    "2017" = "15.0"
    "Visual Studio 2017" = "15.0"
}
$buildToolPaths = @{};
function Get-BuildToolsPath()  {
    Param(
        [String] $Version,

        [Switch] $Latest 
    )

    $buildToolPaths = Get-ModuleVariable "BuildToolPaths"
    if(!$buildToolPaths)
    {
        $buildToolPaths = @{}
        $root = "${Env:ProgramFiles(x86)}\Microsoft Visual Studio";
        $folders = Get-ChildItem "${Env:ProgramFiles(x86)}\Microsoft Visual Studio"
        foreach($folder in $folders) {
            [int] $year = 0
            if([int]::TryParse($folder.Name, [ref] $year)) {
                
                if($year -eq 2017) {
                    $v = "15.0"
                    if(Test-Path "$root\$year\BuildTools") {
                        $buildToolPaths.Add($v, "$root\$year\BuildTools")
                    }
                }
            }
        } 

        Set-ModuleVariable "BuildToolPaths" $buildToolPaths
    }

    if($Latest.ToBool())
    {
        $Version = "Latest"
    }

    if(![string]::IsNullOrWhiteSpace($Version)) {
        if($version.ToLower() -eq "latest") {
            $ceiling = $buildToolPaths.Keys | Sort-Object -Descending | Select-Object -First 1 
            return $buildToolPaths[$ceiling];
        }

        return $buildToolPaths[$version]
    }

   



    $result = @()
    foreach($name in $buildToolPaths.Keys) {
        $result += New-Object PsObject -Property @{
            Name = $name
            Path = $buildToolPaths[$name]
        }
    }

    # Handle Powershell's weird array conversion
    return ,$result
}