Downloads:

1,303,645

Downloads of v 1.5.0:

10,705

Last Update:

06 Oct 2017

Package Maintainer(s):

Software Author(s):

  • Jakub Bereżański

Tags:

chocolatey extension admin visual studio

Chocolatey Visual Studio servicing extensions

This is not the latest version of Chocolatey Visual Studio servicing extensions available.

1.5.0 | Updated: 06 Oct 2017

Downloads:

1,303,645

Downloads of v 1.5.0:

10,705

Maintainer(s):

Software Author(s):

  • Jakub Bereżański

Chocolatey Visual Studio servicing extensions 1.5.0

This is not the latest version of Chocolatey Visual Studio servicing extensions available.

All Checks are Passing

2 Passing Test


Validation Testing Passed


Verification Testing Passed

Details

To install Chocolatey Visual Studio servicing extensions, run the following command from the command line or from PowerShell:

>

To upgrade Chocolatey Visual Studio servicing extensions, run the following command from the command line or from PowerShell:

>

To uninstall Chocolatey Visual Studio servicing extensions, run the following command from the command line or from PowerShell:

>

NOTE: This applies to both open source and commercial editions of Chocolatey.

1. Ensure you are set for organizational deployment

Please see the organizational deployment guide

  • Open Source or Commercial:
    • Proxy Repository - Create a proxy nuget repository on Nexus, Artifactory Pro, or a proxy Chocolatey repository on ProGet. Point your upstream to https://chocolatey.org/api/v2. Packages cache on first access automatically. Make sure your choco clients are using your proxy repository as a source and NOT the default community repository. See source command for more information.
    • You can also just download the package and push it to a repository Download

3. Enter your internal repository url

(this should look similar to https://chocolatey.org/api/v2)

4. Choose your deployment method:


choco upgrade chocolatey-visualstudio.extension -y --source="'STEP 3 URL'" [other options]

See options you can pass to upgrade.

See best practices for scripting.

Add this to a PowerShell script or use a Batch script with tools and in places where you are calling directly to Chocolatey. If you are integrating, keep in mind enhanced exit codes.

If you do use a PowerShell script, use the following to ensure bad exit codes are shown as failures:


choco upgrade chocolatey-visualstudio.extension -y --source="'STEP 3 URL'" 
$exitCode = $LASTEXITCODE

Write-Verbose "Exit code was $exitCode"
$validExitCodes = @(0, 1605, 1614, 1641, 3010)
if ($validExitCodes -contains $exitCode) {
  Exit 0
}

Exit $exitCode

- name: Ensure chocolatey-visualstudio.extension installed
  win_chocolatey:
    name: chocolatey-visualstudio.extension
    state: present
    version: 1.5.0
    source: STEP 3 URL

See docs at https://docs.ansible.com/ansible/latest/modules/win_chocolatey_module.html.

Coming early 2020! Central Managment Reporting available now! More information...


chocolatey_package 'chocolatey-visualstudio.extension' do
  action    :install
  version  '1.5.0'
  source   'STEP 3 URL'
end

See docs at https://docs.chef.io/resource_chocolatey_package.html.


Chocolatey::Ensure-Package
(
    Name: chocolatey-visualstudio.extension,
    Version: 1.5.0,
    Source: STEP 3 URL
);

Requires Otter Chocolatey Extension. See docs at https://inedo.com/den/otter/chocolatey.


cChocoPackageInstaller chocolatey-visualstudio.extension
{
   Name     = 'chocolatey-visualstudio.extension'
   Ensure   = 'Present'
   Version  = '1.5.0'
   Source   = 'STEP 3 URL'
}

Requires cChoco DSC Resource. See docs at https://github.com/chocolatey/cChoco.


package { 'chocolatey-visualstudio.extension':
  provider => 'chocolatey',
  ensure   => '1.5.0',
  source   => 'STEP 3 URL',
}

Requires Puppet Chocolatey Provider module. See docs at https://forge.puppet.com/puppetlabs/chocolatey.


salt '*' chocolatey.install chocolatey-visualstudio.extension version="1.5.0" source="STEP 3 URL"

See docs at https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.chocolatey.html.

5. If applicable - Chocolatey configuration/installation

See infrastructure management matrix for Chocolatey configuration elements and examples.

This package was approved as a trusted package on 06 Oct 2017.

Description

This package provides helper functions useful for developing packages for installing and servicing Microsoft Visual Studio.


CHANGELOG.md
# CHANGELOG

## Version 1.5.0
- New helpers: Add-VisualStudioComponent, Remove-VisualStudioComponent
- New package parameter: '--layout D:\Path' can be used to create an offline installation source ("layout").
  Package installation using this parameter will throw an error at the end (code 814) so that Chocolatey does not register the package as installed.
  Supported by the Install-VisualStudio helper, both for Visual Studio 2017 and 2015.
- New package parameter: '--bootstrapperPath D:\Path\vs_Enterprise.exe' can be used to install Visual Studio from a previously created offline installation source ("layout").
  Supported by the Install-VisualStudio helper, both for Visual Studio 2017 and 2015.
- New helper: Get-VisualStudioInstaller.
  Retrieves an object containing the executable path and version number of the Visual Studio Installer (VS 2017+) installed on the system, if present.
- New helper: Install-VisualStudioInstaller.
  Installs or updates the Visual Studio Installer (VS 2017+).
  Can work from an offline installation source using package parameters, syntax: '--bootstrapperPath D:\Path\vs_Enterprise.exe --offline D:\Path\vs_installer.opc'

## Version 1.4.1
- Fixed encoding of recently added files.

## Version 1.4.0

- Install-VisualStudio can detect existing Visual Studio 2017 products and skip the installation (an interim solution before upgrading is implemented).
- Remove-VisualStudioProduct warns the user not to allow the Chocolatey Auto Uninstaller to run.

## Version 1.3.0

- New helper: Get-VisualStudioInstance.

## Version 1.2.0

- Added switch -IncludeRecommendedComponentsByDefault to Add-VisualStudioWorkload. The user may disable it by passing '--no-includeRecommended' in package parameters.

## Version 1.1.0

- Added helper: Remove-VisualStudioProduct.
- Fixed argument string generation in Start-VisualStudioModifyOperation (affects Add-VisualStudioWorkload and Remove-VisualStudioWorkload).

## Version 1.0.0

- Initial release with helpers: Install-VisualStudio, Uninstall-VisualStudio, Add-VisualStudioWorkload, Remove-VisualStudioWorkload.
- Tested with Visual Studio 2017 and 2015, should also work with earlier Visual Studio versions.
extensions\Add-VisualStudioComponent.ps1
function Add-VisualStudioComponent
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)] [string] $PackageName,
        [Parameter(Mandatory = $true)] [string] $Component,
        [Parameter(Mandatory = $true)] [string] $VisualStudioYear,
        [Parameter(Mandatory = $true)] [string[]] $ApplicableProducts
    )
    if ($Env:ChocolateyPackageDebug -ne $null)
    {
        $VerbosePreference = 'Continue'
        $DebugPreference = 'Continue'
        Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
    }

    Write-Debug "Running 'Add-VisualStudioComponent' with PackageName:'$PackageName' Component:'$Component' VisualStudioYear:'$VisualStudioYear'";
    $argumentList = @('add', "$Component")
    

    Start-VisualStudioModifyOperation -PackageName $PackageName -ArgumentList $argumentList -VisualStudioYear $VisualStudioYear -ApplicableProducts $ApplicableProducts -OperationTexts @('installed', 'installing', 'installation')
}
extensions\Add-VisualStudioWorkload.ps1
function Add-VisualStudioWorkload
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)] [string] $PackageName,
        [Parameter(Mandatory = $true)] [string] $Workload,
        [Parameter(Mandatory = $true)] [string] $VisualStudioYear,
        [Parameter(Mandatory = $true)] [string[]] $ApplicableProducts,
        [switch] $IncludeRecommendedComponentsByDefault
    )
    if ($Env:ChocolateyPackageDebug -ne $null)
    {
        $VerbosePreference = 'Continue'
        $DebugPreference = 'Continue'
        Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
    }

    Write-Debug "Running 'Add-VisualStudioWorkload' with PackageName:'$PackageName' Workload:'$Workload' VisualStudioYear:'$VisualStudioYear' IncludeRecommendedComponentsByDefault:'$IncludeRecommendedComponentsByDefault'";
    $argumentList = @('add', "Microsoft.VisualStudio.Workload.$Workload")
    if ($IncludeRecommendedComponentsByDefault)
    {
        $argumentList += @('includeRecommended', '')
    }

    Start-VisualStudioModifyOperation -PackageName $PackageName -ArgumentList $argumentList -VisualStudioYear $VisualStudioYear -ApplicableProducts $ApplicableProducts -OperationTexts @('installed', 'installing', 'installation')
}
extensions\chocolatey-visualstudio.extension.psm1
Set-StrictMode -Version 2
$ErrorActionPreference = 'Stop'
$scriptRoot = Split-Path -Path $MyInvocation.MyCommand.Definition

$publicFunctions = @(
    'Install-VisualStudio'
    'Uninstall-VisualStudio'
    'Add-VisualStudioWorkload'
    'Add-VisualStudioComponent'
    'Remove-VisualStudioWorkload'
    'Remove-VisualStudioComponent'
    'Remove-VisualStudioProduct'
    'Get-VisualStudioInstance'
    'Get-VisualStudioInstaller'
    'Install-VisualStudioInstaller'
)

Get-ChildItem -Path "$scriptRoot\*.ps1" | ForEach-Object { . $_ }
Export-ModuleMember -Function $publicFunctions
extensions\Generate-AdminFile.ps1
# Generates customizations file. Returns its path
function Generate-AdminFile
{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true)]
        [hashtable] $parameters,
        [string] $adminFile,
        [Parameter(Mandatory = $true)]
        [string] $packageName
    )
    Write-Debug "Running 'Generate-AdminFile' with parameters:'$parameters', defaultAdminFile:'$defaultAdminFile', packageName:'$packageName'";
    $adminFile = $parameters['AdminFile']
    $features = $parameters['Features']
    if ($adminFile -eq '' -and !$features)
    {
        return $null
    }

    $localAdminFile = Join-Path $Env:TEMP "${packageName}_AdminDeployment.xml"
    if (Test-Path $localAdminFile)
    {
        Remove-Item $localAdminFile
    }

    if ($adminFile)
    {
        if (Test-Path $adminFile)
        {
            Copy-Item $adminFile $localAdminFile -force
        }
        else
        {
            if (($adminFile -as [System.URI]).AbsoluteURI -ne $null)
            {
                Get-ChocolateyWebFile 'adminFile' $localAdminFile $adminFile
            }
            else
            {
                throw 'Invalid AdminFile setting.'
            }
        }
        Write-Verbose "Using provided AdminFile: $adminFile"
    }
    elseif ($features)
    {
        Copy-Item $defaultAdminFile $localAdminFile -force
    }

    return $localAdminFile
}
extensions\Generate-InstallArgumentsString.ps1
function Generate-InstallArgumentsString
{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true)]
        [hashtable] $parameters,
        [string] $adminFile,
        [string] $logFilePath,
        [switch] $assumeNewVS2017Installer
    )
    Write-Debug "Running 'Generate-InstallArgumentsString' with parameters:'$parameters', adminFile:'$adminFile', logFilePath:'$logFilePath', assumeNewVS2017Installer:'$assumeNewVS2017Installer'";
    if ($assumeNewVS2017Installer)
    {
        if ($logFilePath -ne '')
        {
            Write-Warning "The new VS 2017 installer does not support setting the path to the log file yet."
        }

        if ($adminFile -ne '')
        {
            Write-Warning "The new VS 2017 installer does not support an admin file yet."
        }

        $argumentSet = $parameters.Clone()
        $argumentSet['wait'] = ''
        if (-not $argumentSet.ContainsKey('layout'))
        {
            $argumentSet['norestart'] = ''
        }
        if (-not $argumentSet.ContainsKey('quiet') -and -not $argumentSet.ContainsKey('passive'))
        {
            $argumentSet['quiet'] = ''
        }

        $s = ($argumentSet.GetEnumerator() | ForEach-Object { '--{0} {1}' -f $_.Key, $_.Value }) -f ' '
    }
    else
    {
        $s = "/Quiet /NoRestart"
        if ($logFilePath -ne '')
        {
            $s = $s + " /Log ""$logFilePath"""
        }

        if ($adminFile -ne '')
        {
            $s = $s + " /AdminFile $adminFile"
        }

        if ($parameters.ContainsKey('layout'))
        {
            # TODO: CHECK THIS, perhaps /NoRestart is incompatible with this?
            $s = $s + " /Layout ""$($parameters['layout'])"""
        }
    }

    $pk = $parameters['ProductKey']
    if ($pk -and (-not [string]::IsNullOrEmpty($pk)))
    {
        Write-Verbose "Using provided product key: ...-$($pk.Substring([Math]::Max($pk.Length - 5, 0)))"
        if ($assumeNewVS2017Installer)
        {
            # nothing to do, all package parameters are passed to Willow
        }
        else
        {
            $s = $s + " /ProductKey $pk"
        }
    }

    return $s
}
extensions\Generate-UninstallArgumentsString.ps1
function Generate-UninstallArgumentsString
{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true)]
        [hashtable] $parameters,
        [string] $logFilePath,
        [switch] $assumeNewVS2017Installer
    )
    Write-Debug "Running 'Generate-UninstallArgumentsString' with logFilePath:'$logFilePath', assumeNewVS2017Installer:'$assumeNewVS2017Installer'";
    if ($assumeNewVS2017Installer)
    {
        if ($logFilePath -ne '')
        {
            Write-Warning "The new VS 2017 installer does not support setting the path to the log file yet."
        }

        $argumentSet = $parameters.Clone()
        $argumentSet['norestart'] = ''
        if (-not $argumentSet.ContainsKey('quiet') -and -not $argumentSet.ContainsKey('passive'))
        {
            $argumentSet['quiet'] = ''
        }

        $s = '/uninstall ' + (($argumentSet.GetEnumerator() | ForEach-Object { '--{0} {1}' -f $_.Key, $_.Value }) -f ' ')
    }
    else
    {
        $s = "/Uninstall /Force /Quiet /NoRestart"
        if ($logFilePath -ne '')
        {
            $s = $s + " /Log ""$logFilePath"""
        }
    }

    return $s
}
extensions\Get-VisualStudioInstaller.ps1
function Get-VisualStudioInstaller
{
<#
.SYNOPSIS
Returns information about the Visual Studio 2017 Installer.

.DESCRIPTION
This function returns an object containing the basic properties (path, version)
of the Visual Studio Installer used by VS 2017 (vs_installer.exe),
if it is present.

.OUTPUTS
A System.Management.Automation.PSObject with the following properties:
Path (System.String)
Version (System.Version)
#>
    [CmdletBinding()]
    Param
    (
    )

    $rxVersion = [regex]'"version":\s+"(?<value>[0-9\.]+)"'
    $basePaths = @(${Env:ProgramFiles}, ${Env:ProgramFiles(x86)}, ${Env:ProgramW6432})
    $installer = $basePaths | Where-Object { $_ -ne $null } | Sort-Object -Unique | ForEach-Object {
        $candidate = Join-Path -Path $_ -ChildPath 'Microsoft Visual Studio\Installer\vs_installer.exe'
        if (Test-Path -Path $candidate)
        {
            Write-Debug "Located VS installer executable: $candidate"
            $version = $null
            $versionJsonPath = Join-Path -Path (Split-Path -Parent -Path $candidate) -ChildPath 'vs_installer.version.json'
            if (Test-Path -Path $versionJsonPath)
            {
                $text = Get-Content -Path $versionJsonPath
                $matches = $rxVersion.Matches($text)
                foreach ($match in $matches)
                {
                    if ($match -eq $null -or -not $match.Success)
                    {
                        continue
                    }

                    $value = $match.Groups['value'].Value
                    try
                    {
                        $version = [version]$value
                    }
                    catch
                    {
                        Write-Warning ('Unable to parse Visual Studio Installer version ''{0}'' ({1})' -f $value, $_)
                    }
                }
            }
            else
            {
                Write-Warning ('Visual Studio Installer version file not found: {0}' -f $versionJsonPath)
            }
            $item = Get-Item -Path $candidate
            $props = @{
                Path = $candidate
                Version = $version
            }
            $obj = New-Object -TypeName PSObject -Property $props
            Write-Verbose ('Visual Studio Installer version {0} is present ({1}).' -f $obj.Version, $obj.Path)
            Write-Output $obj
        }
    }
    $installerCount = ($installer | Measure-Object).Count
    if ($installerCount -eq 0)
    {
        Write-Verbose 'Visual Studio Installer is not present.'
    }
    elseif ($installerCount -gt 1)
    {
        Write-Warning ('Multiple instances of Visual Studio Installer found ({0}), using the first one. This is unexpected, please inform the maintainer of this package.' -f $installerCount)
    }
    $installer | Select-Object -First 1 | Write-Output
}
extensions\Get-VisualStudioInstance.ps1
function Get-VisualStudioInstance
{
<#
.SYNOPSIS
Returns information about installed Visual Studio instances.

.DESCRIPTION
For each Visual Studio instance installed on the machine, this function returns an object
containing the basic properties of the instance.

.OUTPUTS
A System.Management.Automation.PSObject with the following properties:
InstallationPath (System.String)
InstallationVersion (System.Version)
ProductId (System.String; Visual Studio 2017 only)
ChannelId (System.String; Visual Studio 2017 only)
#>
    [CmdletBinding()]
    Param
    (
    )

    Get-WillowInstalledProducts | Where-Object { $_ -ne $null } | ForEach-Object {
        $props = @{
            InstallationPath = $_.installationPath
            InstallationVersion = [version]$_.installationVersion
            ProductId = $_.productId
            ChannelId = $_.channelId
        }
        $obj = New-Object -TypeName PSObject -Property $props
        Write-Output $obj
    }

    Get-VSLegacyInstance | Where-Object { $_ -ne $null } | ForEach-Object {
        $props = @{
            InstallationPath = $_.Path
            InstallationVersion = $_.Version
            ProductId = $null
            ChannelId = $null
        }
        $obj = New-Object -TypeName PSObject -Property $props
        Write-Output $obj
    }
}
extensions\Get-VSLegacyInstance.ps1
function Get-VSLegacyInstance
{
    [CmdletBinding()]
    Param
    (
    )

    Write-Debug 'Detecting Visual Studio products installed using the classic MSI installer (2015 and earlier)'
    $bitness = [IntPtr]::Size * 8
    if ($bitness -eq 64)
    {
        $basePath = 'HKLM:\SOFTWARE\WOW6432Node'
    }
    else
    {
        $basePath = 'HKLM:\SOFTWARE'
    }
    Write-Debug "Process bitness is $bitness, using '$basePath' as base registry path"
    $keyPath = Join-Path -Path $basePath -ChildPath 'Microsoft\VisualStudio\SxS\VS7'
    $classicInstanceCount = 0
    if (-not (Test-Path -Path $keyPath))
    {
        Write-Debug "VS registry key '$keyPath' does not exist."
    }
    else
    {
        Write-Debug "Enumerating properties of key '$keyPath'"
        $props = Get-ItemProperty -Path $keyPath
        $props.PSObject.Properties | Where-Object { $_.Name -match '^\d+\.\d+$' } | ForEach-Object {
            $prop = $_
            Write-Debug ('Found possible classic VS instance: ''{0}'' = ''{1}''' -f $prop.Name, $prop.Value)
            $version = [version]$prop.Name
            if ($version -ge [version]'15.0')
            {
                Write-Debug ('VS instance version is 15.0 or greater, skipping (not a classic instance)')
            }
            else
            {
                $path = $prop.Value
                Write-Verbose ('Found classic VS instance: {0} = ''{1}''' -f $version, $path)
                $instanceProps = @{
                    Version = $version
                    Path = $path
                }
                $instance = New-Object -TypeName PSObject -Property $instanceProps
                Write-Output $instance
                $classicInstanceCount += 1
            }
        }
    }
    if ($classicInstanceCount -eq 0)
    {
        Write-Verbose 'No classic (MSI) Visual Studio installations detected.'
    }
    else
    {
        Write-Verbose "Detected $classicInstanceCount classic (MSI) Visual Studio installations."
    }
}
extensions\Get-VSProductReference.ps1
function Get-VSProductReference
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [string] $VisualStudioYear,
        [Parameter(Mandatory = $true)] [string] $Product
    )

    switch ($VisualStudioYear)
    {
        '2017' { $channelId = 'VisualStudio.15.Release' }
        default { throw "Unsupported VisualStudioYear: $VisualStudioYear"}
    }

    $productId = "Microsoft.VisualStudio.Product." + $Product

    $props = @{
        ChannelId = $channelId
        ProductId = $productId
    }

    $obj = New-Object -TypeName PSObject -Property $props
    return $obj
}
extensions\Get-VSUninstallerExePath.ps1
function Get-VSUninstallerExePath
{
    [CmdletBinding()]
    param(
      [string] $PackageName,
      [string] $UninstallerName,
      [switch] $AssumeNewVS2017Installer,
      [string] $ProgramsAndFeaturesDisplayName
    )

    $informMaintainer = "Please report this to the maintainer of this package ($PackageName)."
    $uninstallKey = Get-VSUninstallRegistryKey -ApplicationName $ProgramsAndFeaturesDisplayName
    $count = ($uninstallKey | Measure-Object).Count
    Write-Debug "Found $count Uninstall key(s)"
    if ($count -eq 0)
    {
        Write-Warning "Uninstall information for $ProgramsAndFeaturesDisplayName could not be found. This probably means the application was uninstalled outside Chocolatey."
        return $null
    }
    if ($count -gt 1)
    {
        throw "More than one Uninstall key found for $ProgramsAndFeaturesDisplayName! $informMaintainer"
    }

    Write-Debug "Using Uninstall key: $($uninstallKey.PSPath)"
    $uninstallString = $uninstallKey | Get-ItemProperty -Name UninstallString | Select-Object -ExpandProperty UninstallString
    Write-Debug "UninstallString: $uninstallString"
    if ($AssumeNewVS2017Installer)
    {
        # C:\Program Files (x86)\Microsoft Visual Studio\Installer\vs_installer.exe /uninstall
        $uninstallerExePathRegexString = '^(.+[^\s])\s/uninstall$'
    }
    else
    {
        # "C:\ProgramData\Package Cache\{4f075c79-8ee3-4c85-9408-828736d1f7f3}\vs_community.exe"  /uninstall
        $uninstallerExePathRegexString = '^\s*(\"[^\"]+\")|([^\s]+)'
    }
    if (-not ($uninstallString -match $uninstallerExePathRegexString))
    {
        throw "UninstallString '$uninstallString' is not of the expected format. $informMaintainer"
    }
    $uninstallerPath = $matches[1].Trim('"')
    Write-Debug "uninstallerPath: $uninstallerPath"
    if ((Split-Path -Path $uninstallerPath -Leaf) -ne $UninstallerName)
    {
        throw "The uninstaller file name is unexpected (uninstallerPath: $uninstallerPath). $informMaintainer"
    }

    return $uninstallerPath
}
extensions\Get-VSUninstallRegistryKey.ps1
function Get-VSUninstallRegistryKey
{
    [CmdletBinding()]
    Param (
        [string] $ApplicationName
    )

    Write-Debug "Looking for Uninstall key for '$ApplicationName'"
    $uninstallKey = @('Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall') `
    | Where-Object { Test-Path -Path $_ } `
    | Get-ChildItem `
    | Where-Object { $displayName = $_ | Get-ItemProperty -Name DisplayName -ErrorAction SilentlyContinue | Select-Object -ExpandProperty DisplayName; $displayName -eq $ApplicationName } `
    | Where-Object { $systemComponent = $_ | Get-ItemProperty -Name SystemComponent -ErrorAction SilentlyContinue | Select-Object -ExpandProperty SystemComponent; $systemComponent -ne 1 }

    return $uninstallKey
}
extensions\Get-WillowInstalledProducts.ps1
function Get-WillowInstalledProducts
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $false)] [string] $VisualStudioYear,
        [Parameter(Mandatory = $false)] [string] $BasePath = "$Env:ProgramData\Microsoft\VisualStudio\Packages\_Instances"
    )

    Write-Debug 'Detecting Visual Studio products installed using the Willow installer (2017+)'
    if (-not (Test-Path -Path $BasePath))
    {
        Write-Debug "Base path '$BasePath' does not exist, assuming no products installed"
        return $null
    }

    $expectedProductProperties = @{
        productLineVersion = 'productLineVersion'
        installationPath = 'installationPath'
        installationVersion = 'installationVersion'
        channelId = 'channelId'
        productId = 'product"\s*:\s*{\s*"id'
    }
    $optionalProductProperties = @{
        nickname = 'nickname'
    }
    $propertyNameSelector = (($expectedProductProperties.Values + $optionalProductProperties.Values) | ForEach-Object { "($_)" }) -join '|'
    $regexTextBasicInfo = '"(?<name>{0})"\s*:\s*"(?<value>[^\"]+)"' -f $propertyNameSelector
    $rxBasicInfo = New-Object -TypeName System.Text.RegularExpressions.Regex -ArgumentList @($regexTextBasicInfo, 'ExplicitCapture,IgnorePatternWhitespace,Singleline')
    $regexTextSingleProductInfo = '\s*{\s*[^}]*"id"\s*:\s*"(?<packageId>[^\"]+)"[^}]*}'
    $rxSelectedPackages = [regex]('"selectedPackages"\s*:\s*\[(({0})(\s*,{0})*)\]' -f $regexTextSingleProductInfo)

    $instanceDataPaths = Get-ChildItem -Path $BasePath | Where-Object { $_.PSIsContainer -eq $true } | Select-Object -ExpandProperty FullName
    foreach ($instanceDataPath in $instanceDataPaths)
    {
        if ($instanceDataPath -eq $null)
        {
            continue
        }

        Write-Debug "Examining possible product instance: $instanceDataPath"
        $stateJsonPath = Join-Path -Path $instanceDataPath -ChildPath 'state.json'
        if (-not (Test-Path -Path $stateJsonPath))
        {
            Write-Warning "File state.json does not exist, this is not a Visual Studio product instance or the file layout has changed! (path: '$instanceDataPath')"
            continue
        }

        $instanceData = @{ selectedPackages = @{} }
        foreach ($name in ($expectedProductProperties.Keys + $optionalProductProperties.Keys))
        {
            $instanceData[$name] = $null
        }

        # unfortunately, PowerShell 2.0 does not have ConvertFrom-Json
        $text = [IO.File]::ReadAllText($stateJsonPath)
        $matches = $rxBasicInfo.Matches($text)
        foreach ($match in $matches)
        {
            if ($match -eq $null -or -not $match.Success)
            {
                continue
            }

            $name = $match.Groups['name'].Value -replace '"id', 'Id' -replace '[^a-zA-Z]', ''
            $value = $match.Groups['value'].Value -replace '\\\\', '\'
            $instanceData[$name] = $value
        }

        Write-Debug ('Parsed instance data: {0}' -f (($instanceData.GetEnumerator() | ForEach-Object { '{0} = ''{1}''' -f $_.Key, $_.Value }) -join ' '))
        $missingExpectedProperties = $expectedProductProperties.GetEnumerator() | Where-Object { -not $instanceData.ContainsKey($_.Key) } | Select-Object -ExpandProperty Key
        if (($missingExpectedProperties | Measure-Object).Count -gt 0)
        {
            Write-Warning "Failed to fully parse state.json, perhaps the file structure has changed! (path: '$stateJsonPath' missing properties: $missingExpectedProperties)"
            continue
        }

        if ($VisualStudioYear -ne '' -and $instanceData.productLineVersion -ne $VisualStudioYear)
        {
            Write-Debug "Skipping product because its productLineVersion ($($instanceData.productLineVersion)) is not equal to VisualStudioYear argument value ($VisualStudioYear)"
            continue
        }

        $match = $rxSelectedPackages.Match($text)
        if ($match.Success)
        {
            foreach ($capture in $match.Groups['packageId'].Captures)
            {
                $packageId = $capture.Value
                $instanceData.selectedPackages[$packageId] = $true
            }
        }

        Write-Debug ('Parsed instance selected packages: {0}' -f ($instanceData.selectedPackages.Keys -join ' '))

        Write-Output $instanceData
    }
}
extensions\Install-VisualStudio.ps1
function Install-VisualStudio {
<#
.SYNOPSIS
Installs Visual Studio

.DESCRIPTION
Installs Visual Studio with ability to specify additional features and supply product key.

.PARAMETER PackageName
The name of the VisualStudio package - this is arbitrary.
It's recommended you call it the same as your nuget package id.

.PARAMETER Url
This is the url to download the VS web installer.

.PARAMETER ChecksumSha1
The SHA-1 hash of the VS web installer file.

.EXAMPLE
Install-VisualStudio -PackageName VisualStudio2015Community -Url 'http://download.microsoft.com/download/zzz/vs_community.exe' -ChecksumSha1 'ABCDEF0123456789ABCDEF0123456789ABCDEF12'

.OUTPUTS
None

.NOTES
This helper reduces the number of lines one would have to write to download and install Visual Studio.
This method has no error handling built into it.

.LINK
Install-ChocolateyPackage
#>
    [CmdletBinding()]
    param(
      [string] $PackageName,
      [string] $ApplicationName,
      [string] $Url,
      [string] $Checksum,
      [string] $ChecksumType,
      [ValidateSet('MsiVS2015OrEarlier', 'WillowVS2017OrLater')] [string] $InstallerTechnology,
      [string] $ProgramsAndFeaturesDisplayName = $ApplicationName,
      [string] $VisualStudioYear,
      [string] $Product
    )
    if ($Env:ChocolateyPackageDebug -ne $null)
    {
        $VerbosePreference = 'Continue'
        $DebugPreference = 'Continue'
        Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
    }
    Write-Debug "Running 'Install-VisualStudio' for $PackageName with ApplicationName:'$ApplicationName' Url:'$Url' Checksum:$Checksum ChecksumType:$ChecksumType InstallerTechnology:'$InstallerTechnology' ProgramsAndFeaturesDisplayName:'$ProgramsAndFeaturesDisplayName' VisualStudioYear:'$VisualStudioYear' Product:'$Product'";

    $packageParameters = Parse-Parameters $env:chocolateyPackageParameters
    $creatingLayout = $packageParameters.ContainsKey('layout')
    $assumeNewVS2017Installer = $InstallerTechnology -eq 'WillowVS2017OrLater'

    if (-not $creatingLayout)
    {
        if ($assumeNewVS2017Installer)
        {
            # there is a single Programs and Features entry for all products, so its presence is not enough
            if ($VisualStudioYear -ne '' -and $Product -ne '')
            {
                $prodRef = Get-VSProductReference -VisualStudioYear $VisualStudioYear -Product $Product
                $products = Get-WillowInstalledProducts | Where-Object { $_ -ne $null -and $_.channelId -eq $prodRef.ChannelId -and $_.productId -eq $prodRef.ProductId }
                $productsCount = ($products | Measure-Object).Count
                Write-Verbose ("Found {0} installed Visual Studio product(s) with ChannelId = {1} and ProductId = {2}" -f $productsCount, $prodRef.ChannelId, $prodRef.ProductId)
                if ($productsCount -gt 0)
                {
                    Write-Warning "$ApplicationName is already installed. Please use the Visual Studio Installer to modify or repair it."
                    return
                }
            }
        }
        else
        {
            $uninstallKey = Get-VSUninstallRegistryKey -ApplicationName $ProgramsAndFeaturesDisplayName
            $count = ($uninstallKey | Measure-Object).Count
            if ($count -gt 0)
            {
                Write-Warning "$ApplicationName is already installed. Please use Programs and Features in the Control Panel to modify or repair it."
                return
            }
        }
    }

    if ($assumeNewVS2017Installer)
    {
        $adminFile = $null
        $logFilePath = $null
    }
    else
    {
        $defaultAdminFile = (Join-Path $PSScriptRoot 'AdminDeployment.xml')
        Write-Debug "Default AdminFile: $defaultAdminFile"

        $adminFile = Generate-AdminFile $packageParameters $defaultAdminFile $PackageName
        Write-Debug "AdminFile: $adminFile"

        Update-AdminFile $packageParameters $adminFile

        $logFilePath = Join-Path $Env:TEMP "${PackageName}.log"
        Write-Debug "Log file path: $logFilePath"
    }

    if ($packageParameters.ContainsKey('bootstrapperPath'))
    {
        $installerFilePath = $packageParameters['bootstrapperPath']
        $packageParameters.Remove('bootstrapperPath')
        Write-Debug "User-provided bootstrapper path: $installerFilePath"
    }
    else
    {
        $installerFilePath = $null
    }

    $silentArgs = Generate-InstallArgumentsString -parameters $packageParameters -adminFile $adminFile -logFilePath $logFilePath -assumeNewVS2017Installer:$assumeNewVS2017Installer

    if ($creatingLayout)
    {
        $layoutPath = $packageParameters['layout']
        Write-Warning "Creating an offline installation source for $PackageName in '$layoutPath'. $PackageName will not be actually installed."
    }

    $arguments = @{
        packageName = $PackageName
        silentArgs = $silentArgs
        url = $Url
        checksum = $Checksum
        checksumType = $ChecksumType
        logFilePath = $logFilePath
        assumeNewVS2017Installer = $assumeNewVS2017Installer
        installerFilePath = $installerFilePath
    }
    $argumentsDump = ($arguments.GetEnumerator() | ForEach-Object { '-{0}:''{1}''' -f $_.Key,"$($_.Value)" }) -join ' '
    Write-Debug "Install-VSChocolateyPackage $argumentsDump"
    Install-VSChocolateyPackage @arguments

    if ($creatingLayout)
    {
        Write-Warning "An offline installation source for $PackageName has been created in '$layoutPath'."
        $bootstrapperExeName = $Url -split '[/\\]' | Select-Object -Last 1
        if ($bootstrapperExeName -like '*.exe')
        {
            Write-Warning "To install $PackageName using this source, pass '--bootstrapperPath $layoutPath\$bootstrapperExeName' as package parameters."
        }
        Write-Warning 'Installation will now be terminated so that Chocolatey does not register this package as installed, do not be alarmed.'
        Set-PowerShellExitCode -exitCode 814
        throw 'An offline installation source has been created; the software has not been actually installed.'
    }
}
extensions\Install-VisualStudioInstaller.ps1
function Install-VisualStudioInstaller
{
<#
.SYNOPSIS
Installs or updates the Visual Studio 2017 Installer.

.DESCRIPTION
This function checks for the presence of the Visual Studio 2017 Installer.
If the Installer is not present, it is installed using the bootstrapper application
(e.g. vs_FeedbackClient.exe), either downloaded from the provided $Url or indicated
via the 'bootstrapperPath' package parameter (which takes precedence).
If the Installer is present, it will be updated/reinstalled if:
- $RequiredVersion was provided and the existing Installer version is lower,
- $RequiredVersion was provided, the existing Installer version is equal and $Force
  was specified,
- $RequiredVersion was not provided and $Force was specified.
#>
    [CmdletBinding()]
    param(
      [string] $PackageName,
      [string] $Url,
      [string] $Checksum,
      [string] $ChecksumType,
      [version] $RequiredVersion,
      [switch] $Force
    )
    if ($Env:ChocolateyPackageDebug -ne $null)
    {
        $VerbosePreference = 'Continue'
        $DebugPreference = 'Continue'
        Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
    }
    Write-Debug "Running 'Install-VisualStudioInstaller' for $PackageName with Url:'$Url' Checksum:$Checksum ChecksumType:$ChecksumType RequiredVersion:'$RequiredVersion' Force:'$Force'";

    $existing = Get-VisualStudioInstaller
    if ($existing -ne $null)
    {
        Write-Debug 'The Visual Studio Installer is already present'
        if ($existing.Version -ne $null -and $RequiredVersion -ne $null)
        {
            if ($existing.Version -lt $RequiredVersion)
            {
                Write-Debug 'The existing Visual Studio Installer version is lower than requested, so it will be updated'
                $shouldUpdate = $true
            }
            elseif ($existing.Version -eq $RequiredVersion)
            {
                if ($Force)
                {
                    Write-Debug 'The existing Visual Studio Installer version is equal to requested, but it will be updated because -Force was used'
                    $shouldUpdate = $true
                }
                else
                {
                    Write-Debug 'The existing Visual Studio Installer version is equal to requested, so it will not be updated'
                    $shouldUpdate = $false
                }
            }
            else
            {
                Write-Debug 'The existing Visual Studio Installer version is greater than requested, so it will not be updated'
                $shouldUpdate = $false
            }
        }
        else
        {
            if ($Force)
            {
                Write-Debug 'The Visual Studio Installer is already present, but it will be updated because -Force was used'
                $shouldUpdate = $true
            }
            else
            {
                Write-Debug 'The Visual Studio Installer is already present and will not be updated'
                $shouldUpdate = $false
            }
        }
    }
    else
    {
        Write-Debug 'The Visual Studio Installer is not present and will be installed'
        $shouldUpdate = $true
    }

    if (-not $shouldUpdate)
    {
        return
    }

    $packageParameters = Parse-Parameters $env:chocolateyPackageParameters

    if ($packageParameters.ContainsKey('bootstrapperPath'))
    {
        $installerFilePath = $packageParameters['bootstrapperPath']
        $packageParameters.Remove('bootstrapperPath')
        Write-Debug "User-provided bootstrapper path: $installerFilePath"
    }
    else
    {
        $installerFilePath = $null
    }

    $silentArgsFromParameters = ($packageParameters.GetEnumerator() | ForEach-Object { '--{0} {1}' -f $_.Key, $_.Value }) -f ' '
    # --update must be last
    $silentArgs = "--quiet $silentArgsFromParameters --update"
    $arguments = @{
        packageName = $PackageName
        silentArgs = $silentArgs
        url = $Url
        checksum = $Checksum
        checksumType = $ChecksumType
        logFilePath = $null
        assumeNewVS2017Installer = $true
        installerFilePath = $installerFilePath
    }
    $argumentsDump = ($arguments.GetEnumerator() | ForEach-Object { '-{0}:''{1}''' -f $_.Key,"$($_.Value)" }) -join ' '
    Write-Debug "Install-VSChocolateyPackage $argumentsDump"
    Install-VSChocolateyPackage @arguments
}
extensions\Install-VSChocolateyInstallPackage.ps1
# based on Install-ChocolateyInstallPackage (fbe24a8), with changes:
# - added recognition of exit codes signifying reboot requirement
# - VS installers are exe
# - dropped support for chocolateyInstallArguments and chocolateyInstallOverride
# - removed unreferenced parameter
# - refactored logic shared with Uninstall-VSChocolateyPackage to a generic function
# - removed exit code parameters in order to centralize exit code logic
function Install-VSChocolateyInstallPackage {
    [CmdletBinding()]
    param(
        [string] $packageName,
        [string] $silentArgs = '',
        [string] $file,
        [string] $logFilePath,
        [switch] $assumeNewVS2017Installer
    )
    Write-Debug "Running 'Install-VSChocolateyInstallPackage' for $packageName with file:'$file', silentArgs:'$silentArgs', logFilePath:'$logFilePath', assumeNewVS2017Installer:'$assumeNewVS2017Installer'"
    $installMessage = "Installing $packageName..."
    Write-Host $installMessage

    if ($file -eq '' -or $file -eq $null) {
        throw 'Package parameters incorrect, File cannot be empty.'
    }

    Start-VSServicingOperation @PSBoundParameters -operationTexts @('installed', 'installing', 'installation')
}
extensions\Install-VSChocolateyPackage.ps1
# based on Install-ChocolateyPackage (a9519b5), with changes:
# - added recognition of exit codes signifying reboot requirement
# - VS installers are exe
# - local file name is extracted from the url (to avoid passing -getOriginalFileName to Get-ChocolateyWebFile for compatibility with old Chocolatey)
# - removed Get-ChocolateyWebFile options support (for compatibility with old Chocolatey)
# - removed exit code parameters in order to centralize exit code logic
function Install-VSChocolateyPackage
{
    [CmdletBinding()]
    param(
        [string] $packageName,
        [string] $silentArgs = '',
        [string] $url,
        [alias("url64")][string] $url64bit = '',
        [string] $checksum = '',
        [string] $checksumType = '',
        [string] $checksum64 = '',
        [string] $checksumType64 = '',
        [string] $logFilePath,
        [switch] $assumeNewVS2017Installer,
        [string] $installerFilePath
    )

    Write-Debug "Running 'Install-VSChocolateyPackage' for $packageName with url:'$url', args:'$silentArgs', url64bit:'$url64bit', checksum:'$checksum', checksumType:'$checksumType', checksum64:'$checksum64', checksumType64:'$checksumType64', logFilePath:'$logFilePath', installerFilePath:'$installerFilePath'";

    if ($installerFilePath -eq '') {
        $chocTempDir = $env:TEMP
        $tempDir = Join-Path $chocTempDir "$packageName"
        if ($env:packageVersion -ne $null) { $tempDir = Join-Path $tempDir "$env:packageVersion" }

        if (![System.IO.Directory]::Exists($tempDir)) { [System.IO.Directory]::CreateDirectory($tempDir) | Out-Null }
        $urlForFileNameDetermination = $url
        if ($urlForFileNameDetermination -eq '') { $urlForFileNameDetermination = $url64bit }
        if ($urlForFileNameDetermination -like '*.exe') { $localFileName = $urlForFileNameDetermination.Substring($urlForFileNameDetermination.LastIndexOfAny(@('/', '\')) + 1) }
        else { $localFileName = 'vs_setup.exe' }
        $localFilePath = Join-Path $tempDir $localFileName

        Write-Verbose "Downloading the installer executable"
        $arguments = @{
            packageName = $packageName
            fileFullPath = $localFilePath
            url = $url
            url64bit = $url64bit
            checksum = $checksum
            checksumType = $checksumType
            checksum64 = $checksum64
            checksumType64 = $checksumType64
        }
        Set-StrictMode -Off
        Get-ChocolateyWebFile @arguments | Out-Null
        Set-StrictMode -Version 2
    } else {
        if (-not (Test-Path -Path $installerFilePath)) {
            throw "The local installer executable does not exist: $installerFilePath"
        }
        Write-Verbose "Using a local installer executable: $installerFilePath"
        $localFilePath = $installerFilePath
    }

    $arguments = @{
        packageName = $packageName
        silentArgs = $silentArgs
        file = $localFilePath
        logFilePath = $logFilePath
        assumeNewVS2017Installer = $assumeNewVS2017Installer
    }
    Install-VSChocolateyInstallPackage @arguments
}
extensions\Parse-Parameters.ps1
# Parse input argument string into a hashtable
# Format: --AdminFile file location --Features WebTools,Win8SDK --ProductKey AB-D1
function Parse-Parameters
{
    [CmdletBinding()]
    Param (
        [string] $s
    )
    Write-Debug "Running 'Parse-Parameters' with s:'$s'";
    $parameters = @{ }

    if ($s -eq '')
    {
        Write-Debug "No package parameters."
        return $parameters
    }

    Write-Debug "Package parameters: $s"
    $s = ' ' + $s
    [String[]] $kvpPrefix = @(" --")
    $kvpDelimiter = ' '

    $kvps = $s.Split($kvpPrefix, [System.StringSplitOptions]::RemoveEmptyEntries)
    foreach ($kvp in $kvps)
    {
        Write-Debug "Package parameter kvp: $kvp"
        $delimiterIndex = $kvp.IndexOf($kvpDelimiter)
        if (($delimiterIndex -le 0) -or ($delimiterIndex -ge ($kvp.Length - 1))) { $delimiterIndex = $kvp.Length }

        $key = $kvp.Substring(0, $delimiterIndex).Trim()
        if ($key -eq '') { continue }
        if ($delimiterIndex -lt $kvp.Length)
        {
            $value = $kvp.Substring($delimiterIndex + 1).Trim()
        }
        else
        {
            $value = ''
        }

        Write-Debug "Package parameter: key=$key, value=$value"
        $parameters.Add($key, $value)
    }

    return $parameters
}
extensions\Remove-VisualStudioComponent.ps1
function Remove-VisualStudioComponent
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)] [string] $PackageName,
        [Parameter(Mandatory = $true)] [string] $Component,
        [Parameter(Mandatory = $true)] [string] $VisualStudioYear,
        [Parameter(Mandatory = $true)] [string[]] $ApplicableProducts
    )
    if ($Env:ChocolateyPackageDebug -ne $null)
    {
        $VerbosePreference = 'Continue'
        $DebugPreference = 'Continue'
        Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
    }

    Write-Debug "Running 'Remove-VisualStudioComponent' with PackageName:'$PackageName' Component:'$Component' VisualStudioYear:'$VisualStudioYear'";
    $argumentList = @('remove', "$Component")

    Start-VisualStudioModifyOperation -PackageName $PackageName -ArgumentList $argumentList -VisualStudioYear $VisualStudioYear -ApplicableProducts $ApplicableProducts -OperationTexts @('uninstalled', 'uninstalling', 'uninstallation')
}
extensions\Remove-VisualStudioProduct.ps1
function Remove-VisualStudioProduct
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)] [string] $PackageName,
        [Parameter(Mandatory = $true)] [string] $Product,
        [Parameter(Mandatory = $true)] [string] $VisualStudioYear
    )
    if ($Env:ChocolateyPackageDebug -ne $null)
    {
        $VerbosePreference = 'Continue'
        $DebugPreference = 'Continue'
        Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
    }

    Write-Debug "Running 'Remove-VisualStudioProduct' with PackageName:'$PackageName' Product:'$Product' VisualStudioYear:'$VisualStudioYear'";
    Start-VisualStudioModifyOperation -PackageName $PackageName -ArgumentList @() -VisualStudioYear $VisualStudioYear -ApplicableProducts @($Product) -OperationTexts @('uninstalled', 'uninstalling', 'uninstallation') -Operation 'uninstall'
    $remainingProductsCount = (Get-WillowInstalledProducts | Measure-Object).Count
    Write-Verbose ("Found {0} installed Visual Studio 2017 or later product(s)" -f $remainingProductsCount)
    if ($remainingProductsCount -gt 0)
    {
        Write-Warning "If Chocolatey asks permission to run the Auto Uninstaller, please answer No. Otherwise, you might lose other Visual Studio products installed on your machine."
    }
}
extensions\Remove-VisualStudioWorkload.ps1
function Remove-VisualStudioWorkload
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)] [string] $PackageName,
        [Parameter(Mandatory = $true)] [string] $Workload,
        [Parameter(Mandatory = $true)] [string] $VisualStudioYear,
        [Parameter(Mandatory = $true)] [string[]] $ApplicableProducts
    )
    if ($Env:ChocolateyPackageDebug -ne $null)
    {
        $VerbosePreference = 'Continue'
        $DebugPreference = 'Continue'
        Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
    }

    Write-Debug "Running 'Remove-VisualStudioWorkload' with PackageName:'$PackageName' Workload:'$Workload' VisualStudioYear:'$VisualStudioYear'";
    Start-VisualStudioModifyOperation -PackageName $PackageName -ArgumentList @('remove', "Microsoft.VisualStudio.Workload.$Workload") -VisualStudioYear $VisualStudioYear -ApplicableProducts $ApplicableProducts -OperationTexts @('uninstalled', 'uninstalling', 'uninstallation')
}
extensions\Set-PowerShellExitCode.ps1
if (-not (Test-Path -Path Function:\Set-PowerShellExitCode))
{
    # based on Set-PowerShellExitCode (07277ac), included here unchanged to add exit code support to old Chocolatey
    function Set-PowerShellExitCode {
        param (
            [int]$exitCode
        )

        $host.SetShouldExit($exitCode); 
        $env:ChocolateyExitCode = $exitCode;
    }
}
extensions\Start-VisualStudioModifyOperation.ps1
function Start-VisualStudioModifyOperation
{
    [CmdletBinding(SupportsShouldProcess = $true)]
    param(
        [Parameter(Mandatory = $true)] [string] $PackageName,
        [AllowEmptyCollection()] [AllowEmptyString()] [Parameter(Mandatory = $true)] [string[]] $ArgumentList,
        [Parameter(Mandatory = $true)] [string] $VisualStudioYear,
        [Parameter(Mandatory = $true)] [string[]] $ApplicableProducts,
        [Parameter(Mandatory = $true)] [string[]] $OperationTexts,
        [ValidateSet('modify', 'uninstall')] [string] $Operation = 'modify',
        [string] $InstallerPath
    )
    Write-Debug "Running 'Start-VisualStudioModifyOperation' with PackageName:'$PackageName' ArgumentList:'$ArgumentList' VisualStudioYear:'$VisualStudioYear' ApplicableProducts:'$ApplicableProducts' OperationTexts:'$OperationTexts' Operation:'$Operation' InstallerPath:'$InstallerPath'";

    $frobbed, $frobbing, $frobbage = $OperationTexts

    if ($InstallerPath -eq '')
    {
        $InstallerPath = Get-VSUninstallerExePath `
                            -PackageName $PackageName `
                            -UninstallerName 'vs_installer.exe' `
                            -ProgramsAndFeaturesDisplayName "Microsoft Visual Studio $VisualStudioYear" `
                            -AssumeNewVS2017Installer

        if ($InstallerPath -eq $null)
        {
            throw "Unable to determine the location of the Visual Studio Installer. Is Visual Studio $VisualStudioYear installed?"
        }
    }

    $packageParameters = Parse-Parameters $env:chocolateyPackageParameters

    for ($i = 0; $i -lt $ArgumentList.Length; $i += 2)
    {
        $packageParameters[$ArgumentList[$i]] = $ArgumentList[$i + 1]
    }

    $packageParameters['norestart'] = ''
    if (-not $packageParameters.ContainsKey('quiet') -and -not $packageParameters.ContainsKey('passive'))
    {
        $packageParameters['quiet'] = ''
    }

    # --no-foo cancels --foo
    $negativeSwitches = $packageParameters.GetEnumerator() | Where-Object { $_.Key -match '^no-.' -and $_.Value -eq '' } | Select-Object -ExpandProperty Key
    foreach ($negativeSwitch in $negativeSwitches)
    {
        if ($negativeSwitch -eq $null)
        {
            continue
        }

        $packageParameters.Remove($negativeSwitch.Substring(3))
        $packageParameters.Remove($negativeSwitch)
    }

    $argumentSets = ,$packageParameters
    if ($packageParameters.ContainsKey('installPath'))
    {
        if ($packageParameters.ContainsKey('productId'))
        {
            Write-Warning 'Parameter issue: productId is ignored when installPath is specified.'
        }

        if ($packageParameters.ContainsKey('channelId'))
        {
            Write-Warning 'Parameter issue: channelId is ignored when installPath is specified.'
        }
    }
    elseif ($packageParameters.ContainsKey('productId'))
    {
        if (-not $packageParameters.ContainsKey('channelId'))
        {
            throw "Parameter error: when productId is specified, channelId must be specified, too."
        }
    }
    elseif ($packageParameters.ContainsKey('channelId'))
    {
        throw "Parameter error: when channelId is specified, productId must be specified, too."
    }
    else
    {
        $installedProducts = Get-WillowInstalledProducts -VisualStudioYear $VisualStudioYear
        if (($installedProducts | Measure-Object).Count -eq 0)
        {
            throw "Unable to detect any supported Visual Studio $VisualStudioYear product. You may try passing --installPath or both --productId and --channelId parameters."
        }

        if ($Operation -eq 'modify')
        {
            if ($packageParameters.ContainsKey('add'))
            {
                $packageIdsList = $packageParameters['add']
                $unwantedPackageSelector = { $productInfo.selectedPackages.ContainsKey($_) }
                $unwantedStateDescription = 'contains'
            }
            elseif ($packageParameters.ContainsKey('remove'))
            {
                $packageIdsList = $packageParameters['remove']
                $unwantedPackageSelector = { -not $productInfo.selectedPackages.ContainsKey($_) }
                $unwantedStateDescription = 'does not contain'
            }
            else
            {
                throw "Unsupported scenario: neither 'add' nor 'remove' is present in parameters collection"
            }
        }
        elseif ($Operation -eq 'uninstall')
        {
            $packageIdsList = ''
            $unwantedPackageSelector = { $false }
            $unwantedStateDescription = '<unused>'
        }
        else
        {
            throw "Unsupported Operation: $Operation"
        }

        $packageIds = ($packageIdsList -split ' ') | ForEach-Object { $_ -split ';' | Select-Object -First 1 }
        $applicableProductIds = $ApplicableProducts | ForEach-Object { "Microsoft.VisualStudio.Product.$_" }
        Write-Debug ('This package supports Visual Studio product id(s): {0}' -f ($applicableProductIds -join ' '))

        $argumentSets = @()
        foreach ($productInfo in $installedProducts)
        {
            $applicable = $false
            $thisProductIds = $productInfo.selectedPackages.Keys | Where-Object { $_ -like 'Microsoft.VisualStudio.Product.*' }
            Write-Debug ('Product at path ''{0}'' has product id(s): {1}' -f $productInfo.installationPath, ($thisProductIds -join ' '))
            foreach ($thisProductId in $thisProductIds)
            {
                if ($applicableProductIds -contains $thisProductId)
                {
                    $applicable = $true
                }
            }

            if (-not $applicable)
            {
                Write-Verbose ('Product at path ''{0}'' will not be modified because it does not support package(s): {1}' -f $productInfo.installationPath, $packageIds)
                continue
            }

            $unwantedPackages = $packageIds | Where-Object $unwantedPackageSelector
            if (($unwantedPackages | Measure-Object).Count -gt 0)
            {
                Write-Verbose ('Product at path ''{0}'' will not be modified because it already {1} package(s): {2}' -f $productInfo.installationPath, $unwantedStateDescription, ($unwantedPackages -join ' '))
                continue
            }

            $argumentSet = $packageParameters.Clone()
            $argumentSet['installPath'] = $productInfo.installationPath
            $argumentSets += $argumentSet
        }
    }

    $overallExitCode = 0
    foreach ($argumentSet in $argumentSets)
    {
        if ($argumentSet.ContainsKey('installPath'))
        {
            Write-Debug "Modifying Visual Studio product: [installPath = '$($argumentSet.installPath)']"
        }
        else
        {
            Write-Debug "Modifying Visual Studio product: [productId = '$($argumentSet.productId)' channelId = '$($argumentSet.channelId)']"
        }

        foreach ($kvp in $argumentSet.Clone().GetEnumerator())
        {
            if ($kvp.Value -match '^(([^"].*\s)|(\s))')
            {
                $argumentSet[$kvp.Key] = '"{0}"' -f $kvp.Value
            }
        }

        $silentArgs = $Operation + (($argumentSet.GetEnumerator() | ForEach-Object { ' --{0} {1}' -f $_.Key, $_.Value }) -join '')
        $exitCode = -1
        if ($PSCmdlet.ShouldProcess("Executable: $InstallerPath", "Start with arguments: $silentArgs"))
        {
            $exitCode = Start-VSChocolateyProcessAsAdmin -statements $silentArgs -exeToRun $InstallerPath -validExitCodes @(0, 3010)
        }

        if ($overallExitCode -eq 0)
        {
            $overallExitCode = $exitCode
        }
    }

    $Env:ChocolateyExitCode = $overallExitCode
    if ($overallExitCode -eq 3010)
    {
        Write-Warning "${PackageName} has been ${frobbed}. However, a reboot is required to finalize the ${frobbage}."
    }
}
extensions\Start-VSChocolateyProcessAsAdmin.ps1
# based on Start-ChocolateyProcessAsAdmin (8734611), included here only slightly modified (renamed, stricter parameter binding), to add exit code support to old Chocolatey
function Start-VSChocolateyProcessAsAdmin {
[CmdletBinding()]
param(
  [string] $statements,
  [string] $exeToRun = 'powershell',
  [switch] $minimized,
  [switch] $noSleep,
  [int[]]$validExitCodes = @(0)
)
  Write-Debug "Running 'Start-VSChocolateyProcessAsAdmin' with exeToRun:'$exeToRun', statements:'$statements', minimized:$minimized, noSleep:$noSleep, validExitCodes:'$validExitCodes'";

  $wrappedStatements = $statements
  if ($wrappedStatements -eq $null) { $wrappedStatements = ''}

  if ($exeToRun -eq 'powershell') {
    $exeToRun = "$($env:SystemRoot)\System32\WindowsPowerShell\v1.0\powershell.exe"
    $importChocolateyHelpers = ""
    Get-ChildItem "$helpersPath" -Filter *.psm1 | ForEach-Object { $importChocolateyHelpers = "& import-module -name  `'$($_.FullName)`';$importChocolateyHelpers" };
    $block = @"
      `$noSleep = `$$noSleep
      $importChocolateyHelpers 
      try{
        `$progressPreference="SilentlyContinue"
        $statements 
        if(!`$noSleep){start-sleep 6}
      }
      catch{
        if(!`$noSleep){start-sleep 8}
        throw
      }
"@
    $encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($block))
    $wrappedStatements = "-NoProfile -ExecutionPolicy bypass -EncodedCommand $encoded"
    $dbgMessage = @"
Elevating Permissions and running powershell block:
$block 
This may take a while, depending on the statements.
"@
  }
  else 
  {
    $dbgMessage = @"
Elevating Permissions and running [`"$exeToRun`" $wrappedStatements]. This may take a while, depending on the statements.
"@
  }
  
  Write-Debug $dbgMessage

  $exeIsTextFile = [System.IO.Path]::GetFullPath($exeToRun) + ".istext"
  if (([System.IO.File]::Exists($exeIsTextFile))) {
    Set-StrictMode -Off
    Set-PowerShellExitCode 4
    throw "The file was a text file but is attempting to be run as an executable - '$exeToRun'"
  }
  
  if ($exeToRun -eq 'msiexec' -or $exeToRun -eq 'msiexec.exe') {
    $exeToRun = "$($env:SystemRoot)\System32\msiexec.exe"
  }

  if (!([System.IO.File]::Exists($exeToRun)) -and $exeToRun -notmatch 'msiexec') {
    Write-Warning "May not be able to find '$exeToRun'. Please use full path for executables."
    # until we have search paths enabled, let's just pass a warning
    #Set-PowerShellExitCode 2
    #throw "Could not find '$exeToRun'"
  }

  # Redirecting output slows things down a bit.
  $writeOutput = {
    if ($EventArgs.Data -ne $null) {
      Write-Host "$($EventArgs.Data)"
    }
  }

  $writeError = {
    if ($EventArgs.Data -ne $null) {
      Write-Error "$($EventArgs.Data)"
    }
  }

  $process = New-Object System.Diagnostics.Process
  $process.EnableRaisingEvents = $true
  Register-ObjectEvent  -InputObject $process -SourceIdentifier "LogOutput_ChocolateyProc" -EventName OutputDataReceived -Action $writeOutput | Out-Null
  Register-ObjectEvent -InputObject $process -SourceIdentifier "LogErrors_ChocolateyProc" -EventName ErrorDataReceived -Action  $writeError | Out-Null

  #$process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo($exeToRun, $wrappedStatements)
  # in case empty args makes a difference, try to be compatible with the older
  # version
  $psi = New-Object System.Diagnostics.ProcessStartInfo
  $psi.FileName = $exeToRun
  if ($wrappedStatements -ne '') {
    $psi.Arguments = "$wrappedStatements"
  }
  $process.StartInfo =  $psi

  # process start info
  $process.StartInfo.RedirectStandardOutput = $true
  $process.StartInfo.RedirectStandardError = $true
  $process.StartInfo.UseShellExecute = $false
  $process.StartInfo.WorkingDirectory = Get-Location
  if ([Environment]::OSVersion.Version -ge (New-Object 'Version' 6,0)){
    Write-Debug "Setting RunAs for elevation"
    $process.StartInfo.Verb = "RunAs"
  }
  if ($minimized) {
    $process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Minimized
  }

  $process.Start() | Out-Null
  if ($process.StartInfo.RedirectStandardOutput) { $process.BeginOutputReadLine() }
  if ($process.StartInfo.RedirectStandardError) { $process.BeginErrorReadLine() }
  $process.WaitForExit()  

  # For some reason this forces the jobs to finish and waits for
  # them to do so. Without this it never finishes.
  Unregister-Event -SourceIdentifier "LogOutput_ChocolateyProc"
  Unregister-Event -SourceIdentifier "LogErrors_ChocolateyProc"

  $exitCode = $process.ExitCode
  $process.Dispose()

  Write-Debug "Command [`"$exeToRun`" $wrappedStatements] exited with `'$exitCode`'."
  if ($validExitCodes -notcontains $exitCode) {
    Set-StrictMode -Off
    Set-PowerShellExitCode $exitCode
    throw "Running [`"$exeToRun`" $statements] was not successful. Exit code was '$exitCode'. See log for possible error messages."
  }
 
  Write-Debug "Finishing 'Start-VSChocolateyProcessAsAdmin'"

  return $exitCode
}
extensions\Start-VSServicingOperation.ps1
function Start-VSServicingOperation
{
    [CmdletBinding()]
    param(
        [string] $packageName,
        [string] $silentArgs,
        [string] $file,
        [string] $logFilePath,
        [string[]] $operationTexts,
        [switch] $assumeNewVS2017Installer
    )
    Write-Debug "Running 'Start-VSServicingOperation' for $packageName with silentArgs:'$silentArgs', file:'$file', logFilePath:$logFilePath', operationTexts:'$operationTexts', assumeNewVS2017Installer:'$assumeNewVS2017Installer'"

    $frobbed, $frobbing, $frobbage = $operationTexts

    $successExitCodes = @(
        0 # success
    )
    $rebootExitCodes = @(
        3010 # success, restart required
    )
    $priorRebootRequiredExitCodes = @(
        -2147185721 # Restart is required before (un)installation can continue
    )
    $blockExitCodes = @(
        -2147205120, # block, restart not required
        -2147172352 # block, restart required
    )

    $validExitCodes = @()
    if (($successExitCodes | Measure-Object).Count -gt 0) { $validExitCodes += $successExitCodes }
    if (($rebootExitCodes | Measure-Object).Count -gt 0) { $validExitCodes += $rebootExitCodes }
    if (($priorRebootRequiredExitCodes | Measure-Object).Count -gt 0) { $validExitCodes += $priorRebootRequiredExitCodes }
    if (($blockExitCodes | Measure-Object).Count -gt 0) { $validExitCodes += $blockExitCodes }

    $exitCode = Start-VSChocolateyProcessAsAdmin -statements $silentArgs -exeToRun $file -validExitCodes $validExitCodes
    if ($assumeNewVS2017Installer)
    {
        # Not only does a process remain running after vs_installer /uninstall finishes, but that process
        # pops up a message box at end! Sheesh.
        Write-Debug 'Looking for vs_installer.windows.exe processes spawned by the uninstaller'
        $installerProcesses = Get-Process -Name 'vs_installer.windows' -ErrorAction SilentlyContinue
        $installerProcessesCount = ($installerProcesses | Measure-Object).Count
        if ($installerProcessesCount -gt 0)
        {
            Write-Debug "Found $installerProcessesCount vs_installer.windows.exe process(es): $($installerProcesses | Select-Object -ExpandProperty Id)"
            Write-Debug "Waiting for all vs_installer.windows.exe processes to become input-idle"
            foreach ($p in $installerProcesses)
            {
                [void] $p.Handle # make sure we get the exit code http://stackoverflow.com/a/23797762/266876
                $p.WaitForInputIdle()
            }
            Write-Debug "Sending CloseMainWindow to all vs_installer.windows.exe processes"
            foreach ($p in $installerProcesses)
            {
                $p.CloseMainWindow()
            }
            Write-Debug "Waiting for all vs_installer.windows.exe processes to exit"
            $installerProcesses | Wait-Process
            foreach ($proc in $installerProcesses)
            {
                if ($proc.ExitCode -ne 0)
                {
                    Write-Warning "vs_installer.windows.exe process $($proc.Id) exited with code $($proc.ExitCode)"
                    if ($exitCode -eq 0)
                    {
                        $exitCode = $proc.ExitCode
                    }
                }
                else
                {
                    Write-Debug "vs_installer.windows.exe process $($proc.Id) exited with code $($proc.ExitCode)"
                }
            }
        }
        else
        {
            Write-Debug 'Did not find any running vs_installer.windows.exe processes.'
        }
    }
    $Env:ChocolateyExitCode = $exitCode
    $warnings = @()
    if (($blockExitCodes | Measure-Object).Count -gt 0 -and $blockExitCodes -contains $exitCode)
    {
        $exceptionMessage = "${packageName} cannot be ${frobbed} on this system."
        $success = $false
        if ($logFilePath -ne '' -and (Test-Path -Path $logFilePath))
        {
            # [0C40:07D8][2016-05-28T23:17:32]i000: MUX:  Stop Block: MinimumOSLevel : This version of Visual Studio requires a computer with a !$!http://go.microsoft.com/fwlink/?LinkID=647155&clcid=0x409!,!newer version of [email protected]!.
            # [0C40:07D8][2016-05-28T23:17:32]i000: MUX:  Stop Block: SystemRebootPendingBlock : The computer needs to be restarted before setup can continue. Please restart the computer and run setup again.
            $blocks = Get-Content -Path $logFilePath `
                | Select-String '(?<=Stop Block: ).+$' `
                | Select-Object -ExpandProperty Matches `
                | Where-Object { $_.Success -eq $true } `
                | Select-Object -ExpandProperty Value `
                | Sort-Object -Unique
            if (($blocks | Measure-Object).Count -gt 0)
            {
                $warnings = @("${packageName} cannot be ${frobbed} due to the following issues:") + $blocks
                $exceptionMessage += " You may attempt to fix the issues listed and try again."
            }
        }
    }
    elseif (($priorRebootRequiredExitCodes | Measure-Object).Count -gt 0 -and $priorRebootRequiredExitCodes -contains $exitCode)
    {
        $exceptionMessage = "The computer must be rebooted before ${frobbing} ${packageName}. Please reboot the computer and run the ${frobbage} again."
        $success = $false
    }
    elseif (($rebootExitCodes | Measure-Object).Count -gt 0 -and $rebootExitCodes -contains $exitCode)
    {
        $needsReboot = $true
        $success = $true
    }
    else
    {
        $needsReboot = $false
        $success = $true
    }

    if ($success)
    {
        if ($needsReboot)
        {
            Write-Warning "${packageName} has been ${frobbed}. However, a reboot is required to finalize the ${frobbage}."
        }
        else
        {
            Write-Host "${packageName} has been ${frobbed}."
        }
    }
    else
    {
        if ($warnings -ne $null)
        {
            $warnings | Write-Warning
        }
        throw $exceptionMessage
    }
}
extensions\Uninstall-VisualStudio.ps1
function Uninstall-VisualStudio {
<#
.SYNOPSIS
Uninstalls Visual Studio

.DESCRIPTION
Uninstalls Visual Studio.

.PARAMETER PackageName
The name of the VisualStudio package.

.PARAMETER ApplicationName
The VisualStudio app name - i.e. 'Microsoft Visual Studio Community 2015'.

.PARAMETER UninstallerName
This name of the installer executable - i.e. 'vs_community.exe'.

.EXAMPLE
Uninstall-VisualStudio 'VisualStudio2015Community' 'Microsoft Visual Studio Community 2015' 'vs_community.exe'

.OUTPUTS
None

.NOTES
This helper reduces the number of lines one would have to write to uninstall Visual Studio.
This method has no error handling built into it.

.LINK
Uninstall-ChocolateyPackage
#>
    [CmdletBinding()]
    param(
      [string] $PackageName,
      [string] $ApplicationName,
      [string] $UninstallerName,
      [ValidateSet('MsiVS2015OrEarlier', 'WillowVS2017OrLater')] [string] $InstallerTechnology,
      [string] $ProgramsAndFeaturesDisplayName = $ApplicationName
    )
    if ($Env:ChocolateyPackageDebug -ne $null)
    {
        $VerbosePreference = 'Continue'
        $DebugPreference = 'Continue'
        Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
    }
    Write-Debug "Running 'Uninstall-VisualStudio' for $PackageName with ApplicationName:'$ApplicationName' UninstallerName:'$UninstallerName' InstallerTechnology:'$InstallerTechnology' ProgramsAndFeaturesDisplayName:'$ProgramsAndFeaturesDisplayName'";

    $assumeNewVS2017Installer = $InstallerTechnology -eq 'WillowVS2017OrLater'

    $uninstallerPath = Get-VSUninstallerExePath `
                        -PackageName $PackageName `
                        -UninstallerName $UninstallerName `
                        -ProgramsAndFeaturesDisplayName $ProgramsAndFeaturesDisplayName `
                        -AssumeNewVS2017Installer:$assumeNewVS2017Installer

    $packageParameters = Parse-Parameters $env:chocolateyPackageParameters
    if ($assumeNewVS2017Installer)
    {
        $logFilePath = $null
    }
    else
    {
        $logFilePath = Join-Path $Env:TEMP "${PackageName}_uninstall.log"
        Write-Debug "Log file path: $logFilePath"
    }

    $silentArgs = Generate-UninstallArgumentsString -parameters $packageParameters -logFilePath $logFilePath -assumeNewVS2017Installer:$assumeNewVS2017Installer

    $arguments = @{
        packageName = $PackageName
        silentArgs = $silentArgs
        file = $uninstallerPath
        assumeNewVS2017Installer = $assumeNewVS2017Installer
    }
    $argumentsDump = ($arguments.GetEnumerator() | ForEach-Object { '-{0}:''{1}''' -f $_.Key,"$($_.Value)" }) -join ' '
    Write-Debug "Uninstall-VSChocolateyPackage $argumentsDump"
    Uninstall-VSChocolateyPackage @arguments
}
extensions\Uninstall-VSChocolateyPackage.ps1
# based on Uninstall-ChocolateyPackage (01db65b), with changes:
# - added recognition of exit codes signifying reboot requirement
# - VS installers are exe
# - dropped support for chocolateyInstallArguments and chocolateyInstallOverride
# - refactored logic shared with Install-VSChocolateyInstallPackage to a generic function
# - removed exit code parameters in order to centralize exit code logic
function Uninstall-VSChocolateyPackage
{
    [CmdletBinding()]
    param(
        [string] $packageName,
        [string] $silentArgs = '',
        [string] $file,
        [switch] $assumeNewVS2017Installer
    )
    Write-Debug "Running 'Uninstall-VSChocolateyPackage' for $packageName with silentArgs:'$silentArgs', file:'$file', assumeNewVS2017Installer:'$assumeNewVS2017Installer'"

    $installMessage = "Uninstalling $packageName..."
    Write-Host $installMessage

    Start-VSServicingOperation @PSBoundParameters -operationTexts @('uninstalled', 'uninstalling', 'uninstallation')
}
extensions\Update-AdminFile.ps1
# Turns on features in the customizations file
function Update-AdminFile
{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true)]
        [hashtable] $parameters,
        [string] $adminFile
    )
    Write-Debug "Running 'Update-AdminFile' with parameters:'$parameters', adminFile:'$adminFile'";
    if ($adminFile -eq '') { return }
    $s = $parameters['Features']
    if (!$s) { return }

    $features = $s.Split(',')
    [xml]$xml = Get-Content $adminFile

    $selectableItemCustomizations = $xml.DocumentElement.SelectableItemCustomizations
    $featuresSelectedByDefault = $selectableItemCustomizations.ChildNodes | Where-Object { $_.GetAttribute('Hidden') -eq 'no' -and $_.GetAttribute('Selected') -eq 'yes' } | Select-Object -ExpandProperty Id
    $selectedFeatures = New-Object System.Collections.ArrayList
    $invalidFeatures = New-Object System.Collections.ArrayList
    foreach ($feature in $features)
    {
        $node = $selectableItemCustomizations.SelectSingleNode("*[@Id=""$feature""]")
        if ($node -ne $null)
        {
            $node.Selected = "yes"
            $selectedFeatures.Add($feature) | Out-Null
        }
        else
        {
            $invalidFeatures.Add($feature) | Out-Null
        }
    }
    if ($invalidFeatures.Count -gt 0)
    {
        $errorMessage = "Invalid feature name(s): $invalidFeatures"
        $validFeatureNames = $selectableItemCustomizations.ChildNodes | Select-Object -ExpandProperty Id
        Write-Warning $errorMessage
        Write-Warning "Valid feature names are: $validFeatureNames"
        throw $errorMessage
    }
    Write-Verbose "Features selected by default: $featuresSelectedByDefault"
    Write-Verbose "Features selected using package parameters: $selectedFeatures"
    $xml.Save($adminFile)
}
README.md
# chocolatey-visualstudio.extension

This is a Chocolatey extension that simplifies building Chocolatey packages which install and configure Microsoft Visual Studio.

## Functions

### Install-VisualStudio

Installs a product from the Visual Studio family (Professional, Enterprise, Community, Build Tools etc.).
Supports both the classic MSI installer of Visual Studio up to 2017 Preview 3 and the new "Willow" installer of Visual Studio 2017 RC.

### Uninstall-VisualStudio

For Visual Studio editions using the classic MSI installer (Visual Studio up to 2017 Preview 3), uninstalls an installed product
from the Visual Studio family (Professional, Enterprise, Community, Build Tools etc.).
For Visual Studio editions using the new "Willow" installer of Visual Studio 2017 RC, uninstalls the Visual Studio Installer
and all installed products from the Visual Studio 2017 family.

### Add-VisualStudioWorkload

Adds a workload (a set of features) to installed products from the Visual Studio 2017 family.
Supports the new "Willow" installer of Visual Studio 2017 RC only.

### Remove-VisualStudioWorkload

Removes a workload (a set of features) from installed products from the Visual Studio 2017 family.
Supports the new "Willow" installer of Visual Studio 2017 RC only.

### Add-VisualStudioComponent

Adds a component (an individual feature) to installed products from the Visual Studio 2017 family.
Supports the new "Willow" installer of Visual Studio 2017 RC only.

### Remove-VisualStudioComponent

Removes a component (an individual feature) from installed products from the Visual Studio 2017 family.
Supports the new "Willow" installer of Visual Studio 2017 RC only.

### Remove-VisualStudioProduct

Removes an installed product from the Visual Studio 2017 family (Professional, Enterprise, Community, Build Tools etc.).
Supports the new "Willow" installer of Visual Studio 2017 RC only.

### Get-VisualStudioInstance

Returns information about all Visual Studio instances installed on the machine.
The returned objects contain properties: InstallationPath, InstallationVersion, ProductId, ChannelId.
The last two properties have values only for instances of Visual Studio 2017.

### Get-VisualStudioInstaller

Returns information about the Visual Studio Installer, if installed on the machine.
The returned object contain properties: Path, Version.
Supports the new "Willow" installer of Visual Studio 2017 RC only.

### Install-VisualStudioInstaller

Installs or updates the Visual Studio Installer.
Supports the new "Willow" installer of Visual Studio 2017 RC only.

## Installation

End users typically do not install this package directly - it is usually installed automatically as a dependency of another package.

Package authors interested in testing the usage of individual functions may install this package via Chocolatey: `choco install chocolatey-visualstudio.extension`.

## Usage

To  be able to use functions from this extension in a Chocolatey package, add the following to the `nuspec` specification:

    <dependencies>
        <dependency id="chocolatey-visualstudio.extension" version="SPECIFY_LATEST_VERSION" />
    </dependencies>

**NOTE**: Make sure you use adequate _minimum_ version.

## Testing

To test the functions you can import the module directly or via the `chocolateyInstaller.psm1` module:

    PS> Import-Module $Env:ChocolateyInstall\helpers\chocolateyInstaller.psm1
    PS> Import-Module $Env:ChocolateyInstall\extensions\chocolatey-visualstudio\*.psm1

You can now test any of the functions:

    PS> Install-VisualStudio `
        -PackageName 'visualstudio2017enterprise' `
        -ApplicationName 'Microsoft Visual Studio Enterprise 2017 RC' `
        -Url 'https://download.microsoft.com/download/4/2/9/429C6D6F-543E-4BB4-A2C7-4EFA7F8DE59D/vs_Enterprise.exe' `
        -Checksum '493364F350657B537077E72E7400DBF8875CD773' `
        -ChecksumType 'SHA1' `
        -InstallerTechnology 'WillowVS2017OrLater' `
        -ProgramsAndFeaturesDisplayName 'Microsoft Visual Studio 2017'

    PS> Add-VisualStudioWorkload `
        -PackageName 'visualstudio2017-workload-manageddesktop' `
        -Workload 'Microsoft.VisualStudio.Workload.ManagedDesktop' `
        -VisualStudioYear '2017' `
        -ApplicableProducts @('Community', 'Professional', 'Enterprise')

    PS> Remove-VisualStudioWorkload `
        -PackageName 'visualstudio2017-workload-manageddesktop' `
        -Workload 'Microsoft.VisualStudio.Workload.ManagedDesktop' `
        -VisualStudioYear '2017' `
        -ApplicableProducts @('Community', 'Professional', 'Enterprise')

    PS> Uninstall-VisualStudio `
        -PackageName 'visualstudio2017enterprise' `
        -ApplicationName 'Microsoft Visual Studio Enterprise 2017 RC' `
        -UninstallerName 'vs_installer.exe' `
        -InstallerTechnology 'WillowVS2017OrLater' `
        -ProgramsAndFeaturesDisplayName 'Microsoft Visual Studio 2017'

    # this must be run from a script and requires the presence of an AdminDeployment.xml file next to the script
    Install-VisualStudio `
        -PackageName 'visualstudio2017enterprise' `
        -ApplicationName 'Microsoft Visual Studio Enterprise 15 Preview 3' `
        -Url 'https://download.microsoft.com/download/e/e/6/ee6e936e-6323-4b51-a6f3-7b276b7e168a/vs_enterprise.exe' `
        -Checksum '6A63984CAFE972D655817395CC12054068077015' `
        -ChecksumType 'SHA1' `
        -InstallerTechnology 'MsiVS2015OrEarlier'

Keep in mind that functions may work fully only in the context of the `chocolateyInstaller` module.

To get the list of functions, load the module directly and invoke the following command:

    Get-Command -Module chocolatey-visualstudio

To get help for a specific function use the [help](https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/get-help) command:

    help Install-VisualStudio -Full

### Acknowledgement

The structure of the Markdown files was inspired by [chocolatey-core.extension](https://github.com/chocolatey/chocolatey-coreteampackages/tree/master/extensions/chocolatey-core.extension).

The module code was initially based on the logic of the `visualstudio2015community` package, later extensively expanded and improved in the `visualstudio2017enterprise` package.

In cases where actual malware is found, the packages are subject to removal. Software sometimes has false positives. Moderators do not necessarily validate the safety of the underlying software, only that a package retrieves software from the official distribution point and/or validate embedded software against official distribution point (where distribution rights allow redistribution).

Chocolatey Pro provides runtime protection from possible malware.

Version Downloads Last Updated Status
Chocolatey Visual Studio servicing extensions 1.8.0 208223 Saturday, March 9, 2019 Approved
Chocolatey Visual Studio servicing extensions 1.8.0-preview4 177 Friday, January 18, 2019 Approved
Chocolatey Visual Studio servicing extensions 1.7.1 195696 Tuesday, November 27, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.7.0 206669 Monday, May 28, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.7.0-rc4 256 Sunday, May 20, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.7.0-rc3 135 Saturday, May 19, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.7.0-rc2 183 Wednesday, May 16, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.6.0 16841 Saturday, March 10, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.6.0-rc9 172 Wednesday, March 7, 2018 Approved

This package has no dependencies.

Discussion for the Chocolatey Visual Studio servicing extensions Package

Ground Rules:

  • This discussion is only about Chocolatey Visual Studio servicing extensions and the Chocolatey Visual Studio servicing extensions package. If you have feedback for Chocolatey, please contact the Google Group.
  • This discussion will carry over multiple versions. If you have a comment about a particular version, please note that in your comments.
  • The maintainers of this Chocolatey Package will be notified about new comments that are posted to this Disqus thread, however, it is NOT a guarantee that you will get a response. If you do not hear back from the maintainers after posting a message below, please follow up by using the link on the left side of this page or follow this link to contact maintainers. If you still hear nothing back, please follow the package triage process.
  • Tell us what you love about the package or Chocolatey Visual Studio servicing extensions, or tell us what needs improvement.
  • Share your experiences with the package, or extra configuration or gotchas that you've found.
  • If you use a url, the comment will be flagged for moderation until you've been whitelisted. Disqus moderated comments are approved on a weekly schedule if not sooner. It could take between 1-5 days for your comment to show up.
comments powered by Disqus