Unpacking Software Livestream

Join our monthly Unpacking Software livestream to hear about the latest news, chat and opinion on packaging, software deployment and lifecycle management!

Learn More

Chocolatey Product Spotlight

Join the Chocolatey Team on our regular monthly stream where we put a spotlight on the most recent Chocolatey product releases. You'll have a chance to have your questions answered in a live Ask Me Anything format.

Learn More

Chocolatey Coding Livestream

Join us for the Chocolatey Coding Livestream, where members of our team dive into the heart of open source development by coding live on various Chocolatey projects. Tune in to witness real-time coding, ask questions, and gain insights into the world of package management. Don't miss this opportunity to engage with our team and contribute to the future of Chocolatey!

Learn More

Calling All Chocolatiers! Whipping Up Windows Automation with Chocolatey Central Management

Webinar from
Wednesday, 17 January 2024

We are delighted to announce the release of Chocolatey Central Management v0.12.0, featuring seamless Deployment Plan creation, time-saving duplications, insightful Group Details, an upgraded Dashboard, bug fixes, user interface polishing, and refined documentation. As an added bonus we'll have members of our Solutions Engineering team on-hand to dive into some interesting ways you can leverage the new features available!

Watch On-Demand
Chocolatey Community Coffee Break

Join the Chocolatey Team as we discuss all things Community, what we do, how you can get involved and answer your Chocolatey questions.

Watch The Replays
Chocolatey and Intune Overview

Webinar Replay from
Wednesday, 30 March 2022

At Chocolatey Software we strive for simple, and teaching others. Let us teach you just how simple it could be to keep your 3rd party applications updated across your devices, all with Intune!

Watch On-Demand
Chocolatey For Business. In Azure. In One Click.

Livestream from
Thursday, 9 June 2022

Join James and Josh to show you how you can get the Chocolatey For Business recommended infrastructure and workflow, created, in Azure, in around 20 minutes.

Watch On-Demand
The Future of Chocolatey CLI

Livestream from
Thursday, 04 August 2022

Join Paul and Gary to hear more about the plans for the Chocolatey CLI in the not so distant future. We'll talk about some cool new features, long term asks from Customers and Community and how you can get involved!

Watch On-Demand
Hacktoberfest Tuesdays 2022

Livestreams from
October 2022

For Hacktoberfest, Chocolatey ran a livestream every Tuesday! Re-watch Cory, James, Gary, and Rain as they share knowledge on how to contribute to open-source projects such as Chocolatey CLI.

Watch On-Demand

Downloads:

17,312,200

Downloads of v 1.8.0:

217,940

Last Update:

09 Mar 2019

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
  • 2
  • 3

1.8.0 | Updated: 09 Mar 2019

Downloads:

17,312,200

Downloads of v 1.8.0:

217,940

Maintainer(s):

Software Author(s):

  • Jakub Bereżański

Chocolatey Visual Studio servicing extensions 1.8.0

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

  • 1
  • 2
  • 3

Some Checks Have Failed or Are Not Yet Complete

Not All Tests Have Passed


Validation Testing Passed


Verification Testing Passed

Details

Scan Testing Resulted in Investigate

Details
Learn More

Deployment Method: Individual Install, Upgrade, & Uninstall

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:

>

Deployment Method:

NOTE

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

1. Enter Your Internal Repository Url

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


2. Setup Your Environment

1. Ensure you are set for organizational deployment

Please see the organizational deployment guide

2. Get the package into your environment

  • 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://community.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. Copy Your Script

choco upgrade chocolatey-visualstudio.extension -y --source="'INTERNAL REPO URL'" --version="'1.8.0'" [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="'INTERNAL REPO URL'" --version="'1.8.0'" 
$exitCode = $LASTEXITCODE

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

Exit $exitCode

- name: Install chocolatey-visualstudio.extension
  win_chocolatey:
    name: chocolatey-visualstudio.extension
    version: '1.8.0'
    source: INTERNAL REPO URL
    state: present

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


chocolatey_package 'chocolatey-visualstudio.extension' do
  action    :install
  source   'INTERNAL REPO URL'
  version  '1.8.0'
end

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


cChocoPackageInstaller chocolatey-visualstudio.extension
{
    Name     = "chocolatey-visualstudio.extension"
    Version  = "1.8.0"
    Source   = "INTERNAL REPO URL"
}

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


package { 'chocolatey-visualstudio.extension':
  ensure   => '1.8.0',
  provider => 'chocolatey',
  source   => 'INTERNAL REPO URL',
}

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


4. If applicable - Chocolatey configuration/installation

See infrastructure management matrix for Chocolatey configuration elements and examples.

Package Approved

This package was approved as a trusted package on 01 Jun 2019.

Description

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


CHANGELOG.md
# CHANGELOG

## Version 1.8.0

- Install-VisualStudio, Add-VisualStudioWorkload/Component and Remove-VisualStudioProduct/Workload/Component now support preview releases (via a new -Preview parameter) and Visual Studio 2019 (-VisualStudioYear 2019).
- Remove-VisualStudioWorkload/Component no longer acts like Add-VisualStudioWorkload/Component if the user passes the '--add' package parameter to `choco uninstall`.
- Fixed determination of outcome of a Visual Studio update operation.
- Visual Studio 2017+ modify/update/uninstall operations now act on either official or preview product instances, but never on both kinds at the same time. This enables developing independent package families for both kinds.
- Fixed installation when current directory is a network share ([GH-59](https://github.com/jberezanski/ChocolateyPackages/issues/59)).

## Version 1.7.1

- Works around an issue in the Visual Studio Installer (https://github.com/electron/electron/issues/12695, https://github.com/nodejs/node/issues/24360) by ensuring the NODE_OPTIONS environment variable is not passed to the Visual Studio Installer ([GH-56](https://github.com/jberezanski/ChocolateyPackages/pull/56)).
- Fixed offline installation from layout ([GH-51](https://github.com/jberezanski/ChocolateyPackages/issues/51)).
- The workaround for undesired vs_Setup.exe behavior when updating the Visual Studio Installer is now only applied to affected vs_Setup.exe versions (15.6.*).

## Version 1.7.0

- New helper: Uninstall-VisualStudioVsixExtension.
- New helper: Get-VisualStudioInstallerHealth (checks for corruption observed sometimes after installer update)
- Install-VisualStudioInstaller will check for installer corruption after update and will attempt to repair the installer by renaming the installer directory and retrying the update.
- The VS Installer will also be repaired before each VS install/update/modify/uninstall operation.
- Before each VS update/modify operation, the required VS Installer version is determined from the channel manifest and the VS Installer is updated (to the newest currently available version, using the VS Bootstrapper) if it does not meet the version requirement. This works around reliability problems in the VS Installer update mechanism if it is triggered during a VS update/modify operation.
- Package parameter '--noUpdateInstaller' can be specified to turn off the VS Installer repair/update logic listed above. To prevent this parameter from being passed to the native installer, specify also '--no-noUpdateInstaller'.
- Package parameter '--installLayoutPath D:\Path' can be specified to indicate the offline installation source for VS workload/component addition (VS product installation/update still needs --bootstrapperPath).
- Package parameter '--noWeb' can be specified for fully offline installation (no Internet access). Works only together with --bootstrapperPath (for product packages) or --installLayoutPath (for workload packages).
- Install-VisualStudio will now update existing VS products. To turn this off, specify '--no-update' in package parameters.

## Version 1.6.0

- New helper: Install-VisualStudioVsixExtension. Supports Visual Studio 2010-2017 and replaces Install-ChocolateyVsixPackage.
- New helper: Get-VisualStudioVsixInstaller.
- Parameters: --add, --remove, --addProductLang and --removeProductLang can now be specified multiple times in package parameters ([GH-16](https://github.com/jberezanski/ChocolateyPackages/issues/16)).
- Parameters: --add, --remove specified in package parameters are no longer ignored when adding/removing workloads and components ([GH-27](https://github.com/jberezanski/ChocolateyPackages/issues/27)).
- New parameter for Add-VisualStudioWorkload and Add-VisualStudioComponent: -RequiredProductVersion. If a workload/component package provides a value for this parameter and a Visual Studio product supported by that package but not meeting this requirement is found, package installation will fail with a message asking the user to upgrade that product.
- ISO mounting feature ported from existing VS 2015 packages. The ISO path can be specified in package parameters as '--IsoPath D:\path\vs.iso' or via an environment variable named 'visualStudio:isoImage'.
 Supported by Install-VisualStudio.
- For compatibility with existing VS 2015 packages, Install-VisualStudio also recognizes an environment variable named 'visualStudio:setupFolder' and will attempt to use the installer executable from there, unless the bootstrapperPath package parameter is present. The installer executable name is obtained from the Url parameter (vs_`<ProductName>`.exe) or, if the Url is not provided or does not contain the executable name, vs_Setup.exe is assumed.
- New package parameter: '--RegenerateAdminFile'. When installing Visual Studio 2015, this parameter instructs the packages to create a fresh admin file by invoking the VS installer with the /CreateAdminFile option, instead of using the default admin file embedded in the package. This can be used to ensure that feature names passed via the --Features package parameter are up to date and will be recognized by the VS installer (some feature names tend to change with minor VS installer updates), because the package will raise an error if one of the features specified by the user is not present in the admin file. Ignored for VS 2017.
- Log files generated during VS 2015 installation now have unique names (with timestamps), preventing overwrite during repeated package installation attempts.
- XML comments in VS 2015 admin files should not cause errors anymore.

## Version 1.5.1

- Changed the method of locating the VS 2017 installer during modify and uninstall operations to not depend on Uninstall registry
  keys anymore. This avoids the problem caused by registry key changes in a recent VS 2017 update.

## 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.
EXAMPLES.md
# Visual Studio 2017 package usage examples

## Product packages

##### Install the latest version of VS 2017 Professional from the Internet or update all installed VS 2017 Professional instances to the latest version. Use the language currently selected in the operating system by the user. Do not display any graphical progress information.

    cinst visualstudio2017professional

##### Install the latest version of VS 2017 Professional from the Internet or update all installed VS 2017 Professional instances to the latest version. Use the English language for the installation process and as the default VS language, also install two more languages. Display the VS Installer window with progress information.

    cinst visualstudio2017professional --params "--locale en-US --addProductLang de-DE --addProductLang fr-FR --passive"

##### Install the latest version of VS 2017 Professional from the Internet only if it is not installed yet (do not attempt to update already installed VS 2017 Professional instances). Use the language currently selected in the operating system by the user. Do not display any graphical progress information.

    cinst visualstudio2017professional --params "--no-update"

##### Create an offline installation source ("layout") for the VS 2017 Build Tools, in English language.

    cinst visualstudio2017buildtools --params "--layout C:\VS 2017 BT 15.7.0 --lang en-US"

##### Install VS 2017 Build Tools or update all installed VS 2017 Build Tools instances, using files from the offline installation source (created earlier) if possible, but downloading any newer files from the Internet.

    cinst visualstudio2017buildtools --params "--bootstrapperPath C:\VS 2017 BT 15.7.0\vs_BuildTools.exe"

##### Install VS 2017 Build Tools or update all installed VS 2017 Build Tools instances, using only files from the offline installation source (created earlier), with no attempts to access the Internet.

    cinst visualstudio2017buildtools --params "--bootstrapperPath C:\VS 2017 BT 15.7.0\vs_BuildTools.exe --noWeb"

##### Install VS 2017 Build Tools or update all installed VS 2017 Build Tools instances, using only files from the offline installation source (created earlier), with no attempts to access the Internet, working around an issue with some older versions of the VS Setup Bootstrapper.

    cinst visualstudio2017buildtools --params "--bootstrapperPath C:\VS 2017 BT 15.5.1\vs_BuildTools.exe --noWeb --no-installLayoutPath"

## Workload packages

##### Add the VCTools workload to all installed VS 2017 Build Tools instances, downloading needed files from the Internet. Required and recommended components will be added, but not optional ones.

    cinst visualstudio2017-workload-vctools

##### Add the VCTools workload to all installed VS 2017 Build Tools instances, downloading needed files from the Internet. All components (required, recommended and optional) will be added.

    cinst visualstudio2017-workload-vctools --params "--includeOptional"

##### Add the VCTools workload to all installed VS 2017 Build Tools instances, using only files from the offline installation source (created earlier), with no attempts to access the Internet. All components (required, recommended and optional) will be added.

    cinst visualstudio2017-workload-vctools --params "--includeOptional --installLayoutPath C:\VS 2017 BT --noWeb"

##### Add the Data workload to all installed VS 2017 Community/Professional/Enterprise instances, downloading needed files from the Internet. Only required components, WebDeploy and the VisualStudioData component will be added.

    cinst visualstudio2017-workload-data --params "--add Microsoft.VisualStudio.Component.WebDeploy --add Microsoft.VisualStudio.Component.VisualStudioData --no-includeRecommended"
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,
        [version] $RequiredProductVersion,
        [bool] $Preview
    )
    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' RequiredProductVersion:'$RequiredProductVersion' Preview:'$Preview'";
    $argumentList = @('add', "$Component")

    $channelReference = Get-VSChannelReference -VisualStudioYear $VisualStudioYear -Preview $Preview
    Start-VSModifyOperation -PackageName $PackageName -ArgumentList $argumentList -ChannelReference $channelReference -ApplicableProducts $ApplicableProducts -RequiredProductVersion $RequiredProductVersion -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,
        [version] $RequiredProductVersion,
        [bool] $Preview
    )
    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' RequiredProductVersion:'$RequiredProductVersion' Preview:'$Preview'";
    $argumentList = @('add', "Microsoft.VisualStudio.Workload.$Workload")
    if ($IncludeRecommendedComponentsByDefault)
    {
        $argumentList += @('includeRecommended', '')
    }

    $channelReference = Get-VSChannelReference -VisualStudioYear $VisualStudioYear -Preview $Preview
    Start-VSModifyOperation -PackageName $PackageName -ArgumentList $argumentList -ChannelReference $channelReference -ApplicableProducts $ApplicableProducts -RequiredProductVersion $RequiredProductVersion -OperationTexts @('installed', 'installing', 'installation')
}
extensions\Assert-VSInstallerUpdated.ps1
function Assert-VSInstallerUpdated
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [string] $PackageName,
        [Parameter(Mandatory = $true)] [hashtable] $PackageParameters,
        [PSObject] $ChannelReference,
        [string] $Url,
        [string] $Checksum,
        [string] $ChecksumType,
        [switch] $UseInstallChannelUri
    )

    if ($PackageParameters.ContainsKey('noUpdateInstaller'))
    {
        Write-Verbose "Skipping update of the VS Installer because --noUpdateInstaller was passed in package parameters"
        return
    }

    $requiredVersionInfo = Get-VSRequiredInstallerVersion -PackageParameters $PackageParameters -ChannelReference $ChannelReference -UseInstallChannelUri:$UseInstallChannelUri
    Install-VSInstaller `
        -RequiredInstallerVersion $requiredVersionInfo.Version `
        -RequiredEngineVersion $requiredVersionInfo.EngineVersion `
        @PSBoundParameters
}
extensions\chocolatey-visualstudio.extension.psm1
Set-StrictMode -Version 2
$ErrorActionPreference = 'Stop'
$scriptRoot = Split-Path -Path $MyInvocation.MyCommand.Definition

Get-ChildItem -Path "$scriptRoot\*.ps1" | ForEach-Object { . $_ }
Export-ModuleMember -Function '*-VisualStudio*'
extensions\Clear-VSChannelCache.ps1
function Clear-VSChannelCache
{
    $localAppData = [Environment]::GetFolderPath([Environment+SpecialFolder]::LocalApplicationData)
    $cachePath = Join-Path -Path $localAppData -ChildPath 'Microsoft\VisualStudio\Packages\_Channels'
    if (Test-Path -Path $cachePath)
    {
        Write-Verbose "Emptying the VS Installer channel cache: '$cachePath'"
        Get-ChildItem -Path $cachePath | Remove-Item -Recurse
    }
}
extensions\Close-VSInstallSource.ps1
function Close-VSInstallSource
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [PSObject] $InstallSourceInfo
    )

    if ($InstallSourceInfo.MountedDiskImage -ne $null)
    {
        Write-Host "Dismounting ISO"
        $InstallSourceInfo.MountedDiskImage | Dismount-DiskImage
    }
    else
    {
        Write-Verbose "No ISO to dismount"
    }
}
extensions\Convert-VSProductReferenceToChannelReference.ps1
function Convert-VSProductReferenceToChannelReference
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [AllowNull()] [PSObject] $ProductReference
    )

    if ($ProductReference -eq $null)
    {
        return $null
    }

    $cr = New-VSChannelReference `
        -ChannelId $ProductReference.ChannelId `
        -ChannelUri $ProductReference.ChannelUri `
        -InstallChannelUri $ProductReference.InstallChannelUri
    return $cr
}
extensions\ConvertTo-ArgumentString.ps1
function ConvertTo-ArgumentString
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [hashtable] $Arguments,
        [Parameter(Mandatory = $true)] [ValidateSet('Willow', 'VSIXInstaller')] [string] $Syntax,
        [string[]] $InitialUnstructuredArguments,
        [string[]] $FinalUnstructuredArguments
    )

    switch ($Syntax)
    {
        'Willow' { $prefix = '--'; $separator = ' ' }
        'VSIXInstaller' { $prefix = '/'; $separator = ':' }
        default { throw "Unknown Syntax parameter value: '$Syntax'" }
    }

    Write-Debug "Generating argument string using prefix = '$prefix', separator = '$separator'"

    $chunks = New-Object System.Collections.Generic.List``1[System.String]
    $rxNeedsQuoting = [regex]'^(([^"].*\s)|(\s))'

    if (($InitialUnstructuredArguments | Measure-Object).Count -gt 0)
    {
        foreach ($val in $InitialUnstructuredArguments)
        {
            if ($rxNeedsQuoting.IsMatch($val))
            {
                $val = """$val"""
            }

            $chunks.Add($val)
        }
    }

    foreach ($kvp in $Arguments.GetEnumerator())
    {
        if ($kvp.Value -eq $null -or ($kvp.Value -isnot [System.Collections.IList] -and [string]::IsNullOrEmpty($kvp.Value)))
        {
            $chunk = '{0}{1}' -f $prefix, $kvp.Key
            $chunks.Add($chunk)
        }
        else
        {
            $vals = $kvp.Value
            if ($vals -isnot [System.Collections.IList])
            {
                $vals = ,$vals
            }

            foreach ($val in $vals)
            {
                if ($rxNeedsQuoting.IsMatch($val))
                {
                    $val = """$val"""
                }

                $chunk = '{0}{1}{2}{3}' -f $prefix, $kvp.Key, $separator, $val
                $chunks.Add($chunk)
            }
        }
    }

    if (($FinalUnstructuredArguments | Measure-Object).Count -gt 0)
    {
        foreach ($val in $FinalUnstructuredArguments)
        {
            if ($rxNeedsQuoting.IsMatch($val))
            {
                $val = """$val"""
            }

            $chunks.Add($val)
        }
    }

    $argsString = $chunks -join ' '
    Write-Debug "Generated argument string: [$argsString]"
    return $argsString
}
extensions\Generate-AdminFile.ps1
# Generates customizations file. Returns its path
function Generate-AdminFile
{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true)]
        [hashtable] $Parameters,
        [Parameter(Mandatory = $true)]
        [string] $DefaultAdminFile,
        [Parameter(Mandatory = $true)]
        [string] $PackageName,
        [Parameter(Mandatory = $true)]
        [PSObject] $InstallSourceInfo,
        [string] $Url,
        [string] $Checksum,
        [string] $ChecksumType
    )
    Write-Debug "Running 'Generate-AdminFile' with Parameters:'$Parameters', DefaultAdminFile:'$DefaultAdminFile', PackageName:'$PackageName', InstallSourceInfo:'$InstallSourceinfo', Url:'$Url', Checksum:'$Checksum', ChecksumType:'$ChecksumType'";
    $adminFile = $Parameters['AdminFile']
    $features = $Parameters['Features']
    $regenerateAdminFile = $Parameters.ContainsKey('RegenerateAdminFile')
    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)
    {
        if (-not $regenerateAdminFile)
        {
            Copy-Item $DefaultAdminFile $localAdminFile -force
        }
        else
        {
            Write-Host "Generating a new admin file using the VS installer"
            $regeneratedAdminFile = $DefaultAdminFile -replace '\.xml$', '.regenerated.xml'
            $logFilePath = Join-Path $Env:TEMP ('{0}_{1:yyyyMMddHHmmss}.log' -f $PackageName, (Get-Date))
            $silentArgs = "/Quiet /NoRestart /Log ""$logFilePath"" /CreateAdminFile ""$regeneratedAdminFile"""
            $arguments = @{
                packageName = $PackageName
                silentArgs = $silentArgs
                url = $Url
                checksum = $Checksum
                checksumType = $ChecksumType
                logFilePath = $logFilePath
                assumeNewVS2017Installer = $false
                installerFilePath = $installSourceInfo.InstallerFilePath
            }
            $argumentsDump = ($arguments.GetEnumerator() | ForEach-Object { '-{0}:''{1}''' -f $_.Key,"$($_.Value)" }) -join ' '
            Write-Debug "Install-VSChocolateyPackage $argumentsDump"
            Install-VSChocolateyPackage @arguments

            Copy-Item $regeneratedAdminFile $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'] = ''
        }

        $nativeInstallerDescription = 'VS Bootstrapper'
        $nativeInstallerArgumentBlacklist = @('bootstrapperPath', 'layoutPath')
        Remove-NegatedArguments -Arguments $argumentSet -RemoveNegativeSwitches
        Remove-VSPackageParametersNotPassedToNativeInstaller -PackageParameters $argumentSet -TargetDescription $nativeInstallerDescription -Blacklist $nativeInstallerArgumentBlacklist

        $s = ConvertTo-ArgumentString -Arguments $argumentSet -Syntax 'Willow'
    }
    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 = ConvertTo-ArgumentString -InitialUnstructuredArguments @('/uninstall') -Arguments $argumentSet -Syntax 'Willow'
    }
    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 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)
EngineVersion (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 {
        $basePath = $_
        $candidateDirPath = Join-Path -Path $basePath -ChildPath 'Microsoft Visual Studio\Installer'
        $candidateDirFiles = Get-ChildItem -Path $candidateDirPath -ErrorAction SilentlyContinue | Where-Object { -not $_.PSIsContainer }
        if (($candidateDirFiles | Measure-Object).Count -gt 0)
        {
            Write-Debug "Located VS installer directory: $candidateDirPath"
            $version = $null
            $versionJsonPath = Join-Path -Path $candidateDirPath -ChildPath 'resources\app\package.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
                        Write-Debug ('Parsed Visual Studio Installer version: {0}' -f $version)
                        break
                    }
                    catch
                    {
                        Write-Warning ('Unable to parse Visual Studio Installer version ''{0}''' -f $value)
                    }
                }
            }
            else
            {
                Write-Warning ('Visual Studio Installer version file not found: {0}' -f $versionJsonPath)
            }
            $engineVersion = $null
            $engineDllPath = Join-Path -Path $candidateDirPath -ChildPath 'resources\app\ServiceHub\Services\Microsoft.VisualStudio.Setup.Service\Microsoft.VisualStudio.Setup.dll'
            if (Test-Path -Path $engineDllPath)
            {
                $item = Get-Item -Path $engineDllPath
                $engineVersionString = $item.VersionInfo.FileVersion
                try
                {
                    $engineVersion = [version]$engineVersionString
                    Write-Debug ('Parsed Visual Studio Installer engine version: {0}' -f $engineVersion)
                }
                catch
                {
                    Write-Warning ('Unable to parse Visual Studio Installer engine version ''{0}''' -f $engineVersionString)
                }
            }
            else
            {
                Write-Warning ('Visual Studio Installer engine file not found: {0}' -f $engineDllPath)
            }
            $installerExePath = Join-Path -Path $candidateDirPath -ChildPath 'vs_installer.exe'
            $props = @{
                Path = $installerExePath
                Version = $version
                EngineVersion = $engineVersion
            }
            $obj = New-Object -TypeName PSObject -Property $props
            Write-Verbose ('Visual Studio Installer version {0} (engine version {1}) is present ({2}).' -f $obj.Version, $obj.EngineVersion, $obj.Path)
            $health = $obj | Get-VisualStudioInstallerHealth
            if (-not $health.IsHealthy)
            {
                if (($health.MissingFiles | Measure-Object).Count -gt 0)
                {
                    Write-Warning ('The Visual Studio Installer in directory ''{0}'' appears broken - missing files: {1}' -f $obj.Path, ($health.MissingFiles -join ', '))
                }
                else
                {
                    Write-Warning ('The Visual Studio Installer in directory ''{0}'' appears broken' -f $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-VisualStudioInstallerHealth.ps1
function Get-VisualStudioInstallerHealth
{
<#
.SYNOPSIS
Checks the Visual Studio Installer for signs of corruption.

.DESCRIPTION
This function returns an object containing the health status
of the Visual Studio Installer, checking for the existence
of a few files observed missing after a failed Installer update.

.OUTPUTS
A System.Management.Automation.PSObject with the following properties:
Path (System.String)
IsHealthy (System.Boolean)
MissingFiles (System.String[])
#>
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [string] $Path
    )
    Process
    {
        if ($Path -like '*.exe')
        {
            $dirPath = Split-Path -Path $Path
        }
        else
        {
            $dirPath = $Path
        }

        $expectedFiles = @('vs_installer.exe', 'vs_installershell.exe', 'node.dll', 'ffmpeg.dll')
        $missingFiles = $expectedFiles | Where-Object { -not (Test-Path (Join-Path -Path $dirPath -ChildPath $_))}
        $obj = New-Object -TypeName PSObject -Property @{
            Path = $Path
            IsHealthy = ($missingFiles | Measure-Object).Count -eq 0
            MissingFiles = $missingFiles
        }

        Write-Output $obj
    }
}
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\New-VSProductReference.ps1
function New-VSProductReference
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [string] $ChannelId,
        [Parameter(Mandatory = $true)] [string] $ProductId,
        [string] $ChannelUri,
        [string] $InstallChannelUri
    )

    $props = @{
        ChannelId = $ChannelId
        ChannelUri = $ChannelUri
        InstallChannelUri = $InstallChannelUri
        ProductId = $ProductId
    }

    $obj = New-Object -TypeName PSObject -Property $props
    return $obj
}
extensions\Open-VSInstallSource.ps1
function Open-VSInstallSource
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [hashtable] $PackageParameters,
        [string] $Url
    )

    $mountedIso = $null
    if ($packageParameters.ContainsKey('bootstrapperPath'))
    {
        $installerFilePath = $packageParameters['bootstrapperPath']
        Write-Debug "User-provided bootstrapper path: $installerFilePath"
    }
    else
    {
        if (Test-Path -Path Env:\visualStudio:setupFolder)
        {
            $setupFolder = "$Env:visualStudio:setupFolder"
            Write-Debug "Setup folder provided via environment variable: $setupFolder"
        }
        else
        {
            $setupFolder = $null
        }

        if ($setupFolder -eq $null -or -not (Test-Path -Path $setupFolder))
        {
            if ($PackageParameters.ContainsKey('IsoImage'))
            {
                $isoPath = $PackageParameters['IsoImage']
                Write-Debug "Using IsoImage from package parameters: $isoPath"
            }
            else
            {
                if (Test-Path -Path Env:\visualStudio:isoImage)
                {
                    $isoPath = "$Env:visualStudio:isoImage"
                    Write-Debug "Using isoImage from environment variable: $isoPath"
                }
                else
                {
                    $isoPath = $null
                }
            }

            if ($isoPath -ne $null)
            {
                $storageModule = Get-Module -ListAvailable -Name Storage
                if ($storageModule -eq $null)
                {
                    throw "ISO mounting is not available on this operating system (requires Windows 8 or later)."
                }

                Write-Host "Mounting ISO image $isoPath"
                $mountedIso = Mount-DiskImage -PassThru -ImagePath $isoPath
                Write-Host "Obtaining drive letter of the mounted ISO image"
                $isoDrive = Get-Volume -DiskImage $mountedIso | Select-Object -ExpandProperty DriveLetter
                Write-Host "Mounted ISO to $isoDrive"
                $setupFolder = "${isoDrive}:\"

                # on some systems the new drive is not recognized by PowerShell until the PSDrive subsystem is "touched"
                # - probably a caching issue inside PowerShell
                Get-PSDrive | Format-Table -AutoSize | Out-String | Write-Debug
                # if it does not immediately resolve the issue, give it some more time
                if (-not (Test-Path -Path $setupFolder))
                {
                    Write-Debug "The new drive has not been recognized by PowerShell yet, giving it some time"
                    $counter = 10
                    do
                    {
                        Write-Debug 'Sleeping for 500 ms'
                        Start-Sleep -Milliseconds 500
                        Get-PSDrive | Format-Table -AutoSize | Out-String | Write-Debug
                        $counter -= 1
                    }
                    while (-not (Test-Path -Path $setupFolder) -and $counter -gt 0)
                    if (-not (Test-Path -Path $setupFolder))
                    {
                        Write-Warning "Unable to test access to the mounted ISO image. Installation will probably fail."
                    }
                }
            }
        }

        if ($setupFolder -ne $null)
        {
            if ($Url -like '*.exe')
            {
                $exeName = Split-Path -Leaf -Path ([uri]$Url).LocalPath
                Write-Debug "Installer executable name determined from url: $exeName"
            }
            else
            {
                $exeName = 'vs_Setup.exe'
                Write-Debug "The installer url does not contain the executable name, using default: $exeName"
            }

            Write-Host "Installing Visual Studio from $setupFolder"
            $installerFilePath = Join-Path -Path $setupFolder -ChildPath $exeName
            Write-Debug "Installer path in setup folder: $installerFilePath"
        }
        else
        {
            $installerFilePath = $null
        }
    }

    if ($installerFilePath -eq $null)
    {
        Write-Verbose "Visual Studio installer will be downloaded from the Web"
    }
    else
    {
        Write-Host "Visual Studio will be installed using $installerFilePath"
    }

    $props = @{
        InstallerFilePath = $installerFilePath
        MountedDiskImage = $mountedIso
    }

    $obj = New-Object -TypeName PSObject -Property $props
    Write-Output $obj
}
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
    }

    $multiValuedParameterNames = @{ add = 1; remove = 1; addProductLang = 1; removeProductLang = 2 }

    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"
        if ($multiValuedParameterNames.ContainsKey($key) -and $parameters.ContainsKey($key))
        {
            $existingValue = $parameters[$key]
            if ($existingValue -is [System.Collections.IList])
            {
                Write-Debug "Parameter is multi-valued, appending to existing list of values"
                $existingValue.Add($value)
            }
            else
            {
                Write-Debug "Parameter is multi-valued, converting value to list of values"
                $parameters[$key] = New-Object -TypeName System.Collections.Generic.List``1[System.String] -ArgumentList (,[string[]]($existingValue, $value))
            }
        }
        else
        {
            $parameters.Add($key, $value)
        }
    }

    return $parameters
}
extensions\Remove-NegatedArguments.ps1
function Remove-NegatedArguments
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [hashtable] $Arguments,
        [switch] $RemoveNegativeSwitches
    )

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

        $parameterToRemove = $negativeSwitch.Substring(3)
        if ($Arguments.ContainsKey($parameterToRemove))
        {
            Write-Debug "Removing negated package parameter: '$parameterToRemove'"
            $Arguments.Remove($parameterToRemove)
        }

        if ($RemoveNegativeSwitches)
        {
            Write-Debug "Removing negative switch: '$negativeSwitch'"
            $Arguments.Remove($negativeSwitch)
        }
    }
}
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-VisualStudioVsixExtension.ps1
function Install-VisualStudioVsixExtension
{
<#
.SYNOPSIS
Installs or updates a Visual Studio VSIX extension.

.DESCRIPTION
This function installs a Visual Studio VSIX extension by invoking
the Visual Studio extension installer (VSIXInstaller.exe).
The latest installer version found on the machine is used.
The extension is installed in all Visual Studio instances present on the
machine the extension is compatible with.

.PARAMETER PackageName
The name of the package - while this is an arbitrary value, it's
recommended that it matches the package id.
Alias: Name

.PARAMETER VsixUrl
The URL of the package to be installed.
Prefer HTTPS when available. Can be HTTP, FTP, or File URIs.
Alias: Url

.PARAMETER Checksum
The checksum hash value of the Url resource. This allows a checksum to
be validated for files that are not local. The checksum type is covered
by ChecksumType.

.PARAMETER ChecksumType
The type of checkum that the file is validated with - valid
values are 'md5', 'sha1', 'sha256' or 'sha512' - defaults to 'md5'.
MD5 is not recommended as certain organizations need to use FIPS
compliant algorithms for hashing - see
https://support.microsoft.com/en-us/kb/811833 for more details.
The recommendation is to use at least SHA256.

.PARAMETER VsVersion
NOT USED. The newest available VSIXInstaller.exe program
will be used and the extension will be installed in all supported
Visual Studio products present on the machine.
Alias: VisualStudioVersion

.PARAMETER Options
Additional options passed to Get-ChocolateyWebFile when downloading
remote resources, such as custom HTTP headers.

.PARAMETER File
Same as VsixUrl, will be used if VsixUrl is empty. Provided for
compatibility reasons.
#>
    [CmdletBinding()]
    Param
    (
        [Alias('Name')] [string] $PackageName,
        [Alias('Url')] [string] $VsixUrl,
        [string] $Checksum,
        [string] $ChecksumType,
        [Alias('VisualStudioVersion')] [int] $VsVersion,
        [hashtable] $Options,
        [string] $File
    )
    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-VisualStudioVsixExtension' for $PackageName with VsixUrl:'$VsixUrl' Checksum:$Checksum ChecksumType:$ChecksumType VsVersion:$VsVersion Options:$Options File:$File";

    $packageParameters = Parse-Parameters $env:chocolateyPackageParameters

    if ($VsVersion -ne 0)
    {
        Write-Warning "VsVersion is not supported yet. The extension will be installed in all compatible Visual Studio instances present."
    }

    if ($VsixUrl -eq '')
    {
        $VsixUrl = $File
    }

    $vsixInstaller = Get-VisualStudioVsixInstaller -Latest
    Write-Verbose ('Found VSIXInstaller version {0}: {1}' -f $vsixInstaller.Version, $vsixInstaller.Path)

    $vsixPath = Get-VSWebFile `
        -PackageName $PackageName `
        -DefaultFileName "${PackageName}.vsix" `
        -FileDescription 'vsix file' `
        -Url $VsixUrl `
        -Checksum $Checksum `
        -ChecksumType $ChecksumType `
        -Options $Options

    $logFileName = 'VSIXInstaller_{0}_{1:yyyyMMddHHmmss}.log' -f $PackageName, (Get-Date)
    $argumentSet = @{
        'quiet' = $null
        'admin' = $null
        'logFile' = $logFileName
    }

    Merge-AdditionalArguments -Arguments $argumentSet -AdditionalArguments $packageParameters
    Remove-NegatedArguments -Arguments $argumentSet -RemoveNegativeSwitches
    $exeArgsString = ConvertTo-ArgumentString -Arguments $argumentSet -Syntax 'VSIXInstaller' -FinalUnstructuredArguments @($vsixPath)

    Write-Host ('Installing {0} using VSIXInstaller version {1}' -f $PackageName, $vsixInstaller.Version)
    $validExitCodes = @(0, 1001)
    $exitCode = Start-VSChocolateyProcessAsAdmin -statements $exeArgsString -exeToRun $vsixInstaller.Path -validExitCodes $validExitCodes
    if ($exitCode -eq 1001)
    {
        Write-Host "Visual Studio extension '${PackageName}' is already installed."
    }
    else
    {
        Write-Host "Visual Studio extension '${PackageName}' has been installed in all supported Visual Studio instances."
    }
}
extensions\Install-VisualStudioInstaller.ps1
function Install-VisualStudioInstaller
{
<#
.SYNOPSIS
Installs or updates the Visual Studio Installer.

.DESCRIPTION
This function checks for the presence of the Visual Studio 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(
      [Parameter(Mandatory = $true)] [string] $PackageName,
      [string] $Url,
      [string] $Checksum,
      [string] $ChecksumType,
      [Alias('RequiredVersion')] [version] $RequiredInstallerVersion,
      [version] $RequiredEngineVersion,
      [ValidateSet('2017', '2019')] [string] $VisualStudioYear = '2017',
      [switch] $Preview,
      [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 RequiredInstallerVersion:'$RequiredInstallerVersion' RequiredEngineVersion:'$RequiredEngineVersion' Force:'$Force'";

    $packageParameters = Parse-Parameters $env:chocolateyPackageParameters

    $channelReference = Get-VSChannelReference -VisualStudioYear $VisualStudioYear -Preview:$Preview
    $PSBoundParameters.Remove('VisualStudioYear')
    $PSBoundParameters.Remove('Preview')

    Install-VSInstaller -PackageParameters $packageParameters -ChannelReference $channelReference @PSBoundParameters
}
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,
      [bool] $Preview,
      [version] $DesiredProductVersion
    )
    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' Preview:'$Preview' DesiredProductVersion:'$DesiredProductVersion'";

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

    $channelReference = $null
    $productReference = $null
    if ($VisualStudioYear -ne '')
    {
        $channelReference = Get-VSChannelReference -VisualStudioYear $VisualStudioYear -Preview $Preview
        if ($Product -ne '')
        {
            $productReference = Get-VSProductReference -ChannelReference $channelReference -Product $Product
        }
    }

    if (-not $creatingLayout)
    {
        if ($assumeNewVS2017Installer)
        {
            # there is a single Programs and Features entry for all products, so its presence is not enough
            if ($productReference -ne $null)
            {
                $products = Resolve-VSProductInstance -ProductReference $productReference -PackageParameters $packageParameters
                $productsCount = ($products | Measure-Object).Count
                Write-Verbose ("Found {0} installed Visual Studio product(s) with ChannelId = {1} and ProductId = {2}" -f $productsCount, $productReference.ChannelId, $productReference.ProductId)
                if ($productsCount -gt 0)
                {
                    $allowUpdate = -not $packageParameters.ContainsKey('no-update')
                    if ($allowUpdate)
                    {
                        Write-Debug 'Updating existing VS instances is enabled (default)'
                        # The bootstrapper is used for updating (either from layout - indicated via bootstrapperPath, or downloaded from $Url).
                        # That way, users can expect that packages using Install-VisualStudio will always call the bootstrapper
                        # and workload packages will always call the installer, so the users will know which arguments will
                        # be supported in each case.
                        Start-VSModifyOperation `
                            -PackageName $PackageName `
                            -ArgumentList @() `
                            -ChannelReference $channelReference `
                            -ApplicableProducts @($Product) `
                            -OperationTexts @('update', 'updating', 'update') `
                            -Operation 'update' `
                            -DesiredProductVersion $DesiredProductVersion `
                            -PackageParameters $packageParameters `
                            -BootstrapperUrl $Url `
                            -BootstrapperChecksum $Checksum `
                            -BootstrapperChecksumType $ChecksumType `
                            -ProductReference $productReference `
                            -UseBootstrapper `
                            -ProductInstance $products
                    }
                    else
                    {
                        Write-Debug 'Updating existing VS instances is disabled because --no-update was passed in package parameters'
                        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
            }
        }
    }

    $installSourceInfo = Open-VSInstallSource -PackageParameters $packageParameters -Url $Url
    try
    {
        if ($assumeNewVS2017Installer)
        {
            $adminFile = $null
            $logFilePath = $null
        }
        else
        {
            $defaultAdminFile = (Join-Path $Env:ChocolateyPackageFolder 'tools\AdminDeployment.xml')
            Write-Debug "Default AdminFile: $defaultAdminFile"

            $adminFile = Generate-AdminFile -Parameters $packageParameters -DefaultAdminFile $defaultAdminFile -PackageName $PackageName -InstallSourceInfo $installSourceInfo -Url $Url -Checksum $Checksum -ChecksumType $ChecksumType
            Write-Debug "AdminFile: $adminFile"

            Update-AdminFile $packageParameters $adminFile

            $logFilePath = Join-Path $Env:TEMP ('{0}_{1:yyyyMMddHHmmss}.log' -f $PackageName, (Get-Date))
            Write-Debug "Log file path: $logFilePath"
        }

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

        if ($assumeNewVS2017Installer)
        {
            Assert-VSInstallerUpdated -PackageName $PackageName -PackageParameters $PackageParameters -ChannelReference $channelReference -Url $Url -Checksum $Checksum -ChecksumType $ChecksumType
        }

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

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

    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\Resolve-VSLayoutPath.ps1
function Resolve-VSLayoutPath
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [hashtable] $PackageParameters
    )

    Write-Debug 'Detecting if a layout path was provided via package parameters'

    if ($PackageParameters.ContainsKey('installLayoutPath'))
    {
        $installLayoutPath = $PackageParameters['installLayoutPath']
        if (-not [string]::IsNullOrEmpty($installLayoutPath))
        {
            Write-Debug "Using installLayoutPath provided via package parameters: $installLayoutPath"
            return $installLayoutPath
        }
        else
        {
            Write-Debug 'Package parameters contain installLayoutPath, but it is empty - ignoring'
        }
    }

    if ($PackageParameters.ContainsKey('bootstrapperPath'))
    {
        $bootstrapperPath = $PackageParameters['bootstrapperPath']
        if (-not [string]::IsNullOrEmpty($bootstrapperPath))
        {
            $installLayoutPath = Split-Path -Path $bootstrapperPath
            Write-Debug "Using installLayoutPath computed from bootstrapperPath provided via package parameters: $installLayoutPath"
            return $installLayoutPath
        }
        else
        {
            Write-Debug 'Package parameters contain $bootstrapperPath, but it is empty - ignoring'
        }
    }

    Write-Debug 'A layout path was not provided via package parameters'
    return $null
}
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'
        channelUri = 'channelUri'
        productId = 'product"\s*:\s*{\s*"id'
        enginePath = 'enginePath'
    }
    $optionalProductProperties = @{
        nickname = 'nickname'
        installChannelUri = 'installChannelUri'
    }
    $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\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-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 = "${Env:SystemDrive}\"
  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
  }
  # The Visual Studio Installer uses Electron, some versions can crash if NODE_OPTIONS is set
  # https://github.com/electron/electron/issues/12695
  # https://github.com/nodejs/node/issues/24360
  $process.StartInfo.EnvironmentVariables.Remove("NODE_OPTIONS") | Out-Null

  $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-VSModifyOperation.ps1
function Start-VSModifyOperation
{
    [CmdletBinding(SupportsShouldProcess = $true)]
    param(
        [Parameter(Mandatory = $true)] [string] $PackageName,
        [AllowEmptyCollection()] [AllowEmptyString()] [Parameter(Mandatory = $true)] [string[]] $ArgumentList,
        [Parameter(Mandatory = $true)] [PSObject] $ChannelReference,
        [Parameter(Mandatory = $true)] [string[]] $ApplicableProducts,
        [Parameter(Mandatory = $true)] [string[]] $OperationTexts,
        [ValidateSet('modify', 'uninstall', 'update')] [string] $Operation = 'modify',
        [version] $RequiredProductVersion,
        [version] $DesiredProductVersion,
        [hashtable] $PackageParameters,
        [string] $BootstrapperUrl,
        [string] $BootstrapperChecksum,
        [string] $BootstrapperChecksumType,
        [PSObject] $ProductReference,
        [switch] $UseBootstrapper,
        [PSObject[]] $ProductInstance
    )
    Write-Debug "Running 'Start-VSModifyOperation' with PackageName:'$PackageName' ArgumentList:'$ArgumentList' ChannelReference:'$ChannelReference' ApplicableProducts:'$ApplicableProducts' OperationTexts:'$OperationTexts' Operation:'$Operation' RequiredProductVersion:'$RequiredProductVersion' BootstrapperUrl:'$BootstrapperUrl' BootstrapperChecksum:'$BootstrapperChecksum' BootstrapperChecksumType:'$BootstrapperChecksumType' ProductReference:'$ProductReference' UseBootstrapper:'$UseBootstrapper'";

    if ($ProductReference -eq $null -and $Operation -eq 'update')
    {
        throw 'ProductReference is mandatory for update operations.'
    }

    $frobbed, $frobbing, $frobbage = $OperationTexts

    if ($PackageParameters -eq $null)
    {
        $PackageParameters = Parse-Parameters $env:chocolateyPackageParameters
    }
    else
    {
        $PackageParameters = $PackageParameters.Clone()
    }

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

    $baseArgumentSet = $argumentSetFromArgumentList.Clone()
    Merge-AdditionalArguments -Arguments $baseArgumentSet -AdditionalArguments $packageParameters
    @('add', 'remove') | Where-Object { $argumentSetFromArgumentList.ContainsKey($_) } | ForEach-Object `
    {
        $value = $argumentSetFromArgumentList[$_]
        $existingValue = $baseArgumentSet[$_]
        if ($existingValue -is [System.Collections.IList])
        {
            if ($existingValue -notcontains $value)
            {
                Write-Debug "Adding back argument '$_' value '$value' (adding to existing list)"
                [void]$existingValue.Add($value)
            }
        }
        else
        {
            if ($existingValue -ne $value)
            {
                Write-Debug "Adding back argument '$_' value '$value' (converting to list)"
                $baseArgumentSet[$_] = New-Object -TypeName System.Collections.Generic.List``1[System.String] -ArgumentList (,[string[]]($existingValue, $value))
            }
        }
    }

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

        if ($baseArgumentSet.ContainsKey('channelId'))
        {
            Write-Warning 'Parameter issue: channelId is ignored when installPath is specified.'
        }

        $installedProducts = Resolve-VSProductInstance -AnyProductAndChannel -PackageParameters $PackageParameters
        if (($installedProducts | Measure-Object).Count -gt 0)
        {
            # Should be only one, but it is not guaranteed, hence the loop.
            foreach ($productInfo in $installedProducts)
            {
                if ($productInfo.channelId -ne $ChannelReference.ChannelId)
                {
                    Write-Warning "Product at path '$($productInfo.installationPath)' has channel id '$($productInfo.channelId)', expected '$($ChannelReference.ChannelId)'."
                }

                if ($ProductReference -ne $null -and $productInfo.productId -ne $ProductReference.ProductId)
                {
                    Write-Warning "Product at path '$($productInfo.installationPath)' has product id '$($productInfo.productId)', expected '$($ProductReference.ProductId)'."
                }

                $baseArgumentSet['__internal_productReference'] = New-VSProductReference -ChannelId $productInfo.channelId -ProductId $productInfo.productId -ChannelUri $productInfo.channelUri -InstallChannelUri $productInfo.installChannelUri
            }
        }
        else
        {
            Write-Warning "Did not detect any installed Visual Studio products at path $($baseArgumentSet['installPath'])."
        }
    }
    elseif ($baseArgumentSet.ContainsKey('productId'))
    {
        if (-not $baseArgumentSet.ContainsKey('channelId'))
        {
            throw "Parameter error: when productId is specified, channelId must be specified, too."
        }

        $baseArgumentSet['__internal_productReference'] = New-VSProductReference -ChannelId $baseArgumentSet['channelId'] -ProductId $baseArgumentSet['productId']
    }
    elseif ($baseArgumentSet.ContainsKey('channelId'))
    {
        throw "Parameter error: when channelId is specified, productId must be specified, too."
    }
    else
    {
        if (($ProductInstance | Measure-Object).Count -ne 0)
        {
            $installedProducts = $ProductInstance
        }
        else
        {
            $installedProducts = Resolve-VSProductInstance -ChannelReference $ChannelReference -PackageParameters $PackageParameters
            if (($installedProducts | Measure-Object).Count -eq 0)
            {
                throw "Unable to detect any supported Visual Studio product. You may try passing --installPath or both --productId and --channelId parameters."
            }
        }

        if ($Operation -eq 'modify')
        {
            # The VS instance filtering logic should be based on the primary operation,
            # i.e. 'add' for Add-VisualStudio* and 'remove' for Remove-VisualStudio*.
            # This can be extrapolated from ArgumentList, which is only set by those cmdlets, so trustworthy.
            $addArgumentIsPresent = $ArgumentList -contains 'add'
            $removeArgumentIsPresent = $ArgumentList -contains 'remove'
            if ($addArgumentIsPresent -and $removeArgumentIsPresent)
            {
                throw "Unsupported scenario: both 'add' and 'remove' are present in ArgumentList"
            }
            elseif ($addArgumentIsPresent)
            {
                $packageIdsList = $baseArgumentSet['add']
                $unwantedPackageSelector = { $productInfo.selectedPackages.ContainsKey($_) }
                $unwantedStateDescription = 'contains'
            }
            elseif ($removeArgumentIsPresent)
            {
                $packageIdsList = $baseArgumentSet['remove']
                $unwantedPackageSelector = { -not $productInfo.selectedPackages.ContainsKey($_) }
                $unwantedStateDescription = 'does not contain'
            }
            else
            {
                throw "Unsupported scenario: neither 'add' nor 'remove' is present in ArgumentList"
            }
        }
        elseif (@('uninstall', 'update') -contains $Operation)
        {
            $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)
            {
                if (($packageIds | Measure-Object).Count -gt 0)
                {
                    Write-Verbose ('Product at path ''{0}'' will not be modified because it does not support package(s): {1}' -f $productInfo.installationPath, $packageIds)
                }
                else
                {
                    Write-Verbose ('Product at path ''{0}'' will not be modified because it is not present on the list of applicable products: {1}' -f $productInfo.installationPath, $ApplicableProducts)
                }

                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
            }

            $existingProductVersion = [version]$productInfo.installationVersion
            if ($RequiredProductVersion -ne $null)
            {
                if ($existingProductVersion -lt $RequiredProductVersion)
                {
                    throw ('Product at path ''{0}'' will not be modified because its version ({1}) is lower than the required minimum ({2}). Please update the product first and reinstall this package.' -f $productInfo.installationPath, $existingProductVersion, $RequiredProductVersion)
                }
                else
                {
                    Write-Verbose ('Product at path ''{0}'' will be modified because its version ({1}) satisfies the version requirement of {2} or higher.' -f $productInfo.installationPath, $existingProductVersion, $RequiredProductVersion)
                }
            }

            if ($Operation -eq 'update' -and $DesiredProductVersion -ne $null)
            {
                if ($DesiredProductVersion -le $existingProductVersion)
                {
                    Write-Verbose ('Product at path ''{0}'' will not be updated because its version ({1}) is greater than or equal to the desired version of {2}.' -f $productInfo.installationPath, $existingProductVersion, $DesiredProductVersion)
                    continue
                }
                else
                {
                    Write-Debug ('Product at path ''{0}'' will be updated because its version ({1}) is lower than the desired version of {2}.' -f $productInfo.installationPath, $existingProductVersion, $DesiredProductVersion)
                }
            }

            $argumentSet = $baseArgumentSet.Clone()
            $argumentSet['installPath'] = $productInfo.installationPath
            $argumentSet['__internal_productReference'] = New-VSProductReference -ChannelId $productInfo.channelId -ProductId $productInfo.productId -ChannelUri $productInfo.channelUri -InstallChannelUri $productInfo.installChannelUri
            $argumentSets += $argumentSet
        }
    }

    $layoutPath = Resolve-VSLayoutPath -PackageParameters $baseArgumentSet
    $nativeInstallerPath = $null
    if ($UseBootstrapper)
    {
        $nativeInstallerDescription = 'VS Bootstrapper'
        $nativeInstallerArgumentBlacklist = @('bootstrapperPath', 'layoutPath')
        $layoutPathArgumentName = 'installLayoutPath'
        if ($baseArgumentSet.ContainsKey('bootstrapperPath'))
        {
            $nativeInstallerPath = $baseArgumentSet['bootstrapperPath']
            Write-Debug "Using bootstrapper path from package parameters: $nativeInstallerPath"
        }
        elseif ($BootstrapperUrl -ne '')
        {
            Write-Debug "Using bootstrapper url: $BootstrapperUrl"
        }
        else
        {
            throw 'When -UseBootstrapper is specified, BootstrapperUrl must not be empty and/or package parameters must contain bootstrapperPath'
        }
    }
    else
    {
        $nativeInstallerDescription = 'VS Installer'
        $nativeInstallerArgumentBlacklist = @('bootstrapperPath', 'installLayoutPath', 'wait')
        $layoutPathArgumentName = 'layoutPath'
    }

    Write-Debug "The $nativeInstallerDescription will be used as the native installer"

    $installer = $null
    $installerUpdated = $false
    $channelCacheCleared = $false
    $overallExitCode = 0
    foreach ($argumentSet in $argumentSets)
    {
        if ($argumentSet.ContainsKey('installPath'))
        {
            $productDescription = "Visual Studio product: [installPath = '$($argumentSet.installPath)']"
        }
        else
        {
            $productDescription = "Visual Studio product: [productId = '$($argumentSet.productId)' channelId = '$($argumentSet.channelId)']"
        }

        Write-Debug "Modifying $productDescription"

        $thisProductReference = $ProductReference
        if ($argumentSet.ContainsKey('__internal_productReference'))
        {
            $thisProductReference = $argumentSet['__internal_productReference']
            $argumentSet.Remove('__internal_productReference')
        }

        $thisChannelReference = $ChannelReference
        if ($thisProductReference -ne $null)
        {
            $thisChannelReference = Convert-VSProductReferenceToChannelReference -ProductReference $thisProductReference
        }

        $shouldFixInstaller = $false
        if ($installer -eq $null)
        {
            $installer = Get-VisualStudioInstaller
            if ($installer -eq $null)
            {
                $shouldFixInstaller = $true
            }
            else
            {
                $health = $installer | Get-VisualStudioInstallerHealth
                $shouldFixInstaller = -not $health.IsHealthy
            }
        }

        if ($shouldFixInstaller -or ($Operation -ne 'uninstall' -and -not $installerUpdated))
        {
            if ($Operation -ne 'update' -and $argumentSet.ContainsKey('noWeb'))
            {
                Write-Debug 'InstallChannelUri will be used for VS Installer update because operation is not "update" and --noWeb was passed in package parameters'
                $useInstallChannelUri = $true
            }
            else
            {
                Write-Debug 'InstallChannelUri will not be used for VS Installer update because either operation is "update" or --noWeb was not passed in package parameters'
                $useInstallChannelUri = $false
            }

            if ($PSCmdlet.ShouldProcess("Visual Studio Installer", "update"))
            {
                Assert-VSInstallerUpdated -PackageName $PackageName -PackageParameters $PackageParameters -ChannelReference $thisChannelReference -Url $BootstrapperUrl -Checksum $BootstrapperChecksum -ChecksumType $BootstrapperChecksumType -UseInstallChannelUri:$useInstallChannelUri
                $installerUpdated = $true
                $shouldFixInstaller = $false
                $installer = Get-VisualStudioInstaller
            }
        }

        if (-not $UseBootstrapper)
        {
            if ($installer -eq $null)
            {
                throw 'The Visual Studio Installer is not present. Unable to continue.'
            }
            else
            {
                $nativeInstallerPath = $installer.Path
            }
        }

        if ($Operation -ne 'uninstall' -and -not $channelCacheCleared)
        {
            # this works around concurrency issues in recent VS Installer versions (1.14.x),
            # which lead to product updates not being detected
            # due to the VS Installer failing to update the cached manifests (file in use)
            if ($PSCmdlet.ShouldProcess("Visual Studio Installer channel cache", "clear"))
            {
                Clear-VSChannelCache
                $channelCacheCleared = $true
            }
        }

        # if updating/modifying from layout, auto add --layoutPath (VS Installer) or --installLayoutPath (VS Bootstrapper)
        if (-not $argumentSet.ContainsKey($layoutPathArgumentName))
        {
            if ($layoutPath -ne $null)
            {
                Write-Debug "Using layout path: $layoutPath"
                $argumentSet[$layoutPathArgumentName] = $layoutPath
                if ($UseBootstrapper)
                {
                    Write-Debug 'Note: some older versions of the VS Setup Bootstrapper do not recognize the --installLayoutPath argument and, instead of consuming it, pass it unmodified to the VS Installer, which does not recognize it and signals an error. If installation fails, try suppressing the usage of this argument by passing --no-installLayoutPath in package parameters.'
                }
            }
        }

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

        Remove-NegatedArguments -Arguments $argumentSet -RemoveNegativeSwitches
        Remove-VSPackageParametersNotPassedToNativeInstaller -PackageParameters $argumentSet -TargetDescription $nativeInstallerDescription -Blacklist $nativeInstallerArgumentBlacklist

        $silentArgs = ConvertTo-ArgumentString -InitialUnstructuredArguments @($Operation) -Arguments $argumentSet -Syntax 'Willow'

        $exitCode = -1
        $processed = $false
        if ($PSCmdlet.ShouldProcess("Executable: $nativeInstallerPath", "Install-VSChocolateyPackage with arguments: $silentArgs"))
        {
            $arguments = @{
                packageName = $PackageName
                silentArgs = $silentArgs
                url = $BootstrapperUrl
                checksum = $BootstrapperChecksum
                checksumType = $BootstrapperChecksumType
                logFilePath = $null
                assumeNewVS2017Installer = $true
                installerFilePath = $nativeInstallerPath
            }
            $argumentsDump = ($arguments.GetEnumerator() | ForEach-Object { '-{0}:''{1}''' -f $_.Key,"$($_.Value)" }) -join ' '
            Write-Debug "Install-VSChocolateyPackage $argumentsDump"
            Install-VSChocolateyPackage @arguments
            $exitCode = [int]$Env:ChocolateyExitCode
            Write-Debug "Exit code set by Install-VSChocolateyPackage: '$exitCode'"
            $processed = $true
        }

        if ($processed -and $Operation -eq 'update')
        {
            $instance = Resolve-VSProductInstance -ProductReference $thisProductReference -PackageParameters $argumentSet
            $instanceCount = ($instance | Measure-Object).Count
            if ($instanceCount -eq 1)
            {
                $currentProductVersion = [version]$instance.installationVersion
                if ($DesiredProductVersion -ne $null)
                {
                    if ($currentProductVersion -ge $DesiredProductVersion)
                    {
                        Write-Debug "After update operation, $productDescription is at version $currentProductVersion, which is greater than or equal to the desired version ($DesiredProductVersion)."
                    }
                    else
                    {
                        throw "After update operation, $productDescription is at version $currentProductVersion, which is lower than the desired version ($DesiredProductVersion). This means the update failed."
                    }
                }

                Write-Verbose "$productDescription is now at version $currentProductVersion."
            }
            elseif ($instanceCount -eq 0)
            {
                Write-Warning "Unable to detect the updated $productDescription instance. This might mean that update failed. "
            }
        }

        if ($overallExitCode -eq 0)
        {
            Write-Debug "Setting overall exit code to '$exitCode'"
            $overallExitCode = $exitCode
        }
    }

    Write-Debug "Setting Env:ChocolateyExitCode to overall exit code: '$overallExitCode'"
    $Env:ChocolateyExitCode = $overallExitCode
    if ($overallExitCode -eq 3010)
    {
        Write-Warning "${PackageName} has been ${frobbed}. However, a reboot is required to finalize the ${frobbage}."
    }
}
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'"

    Wait-VSInstallerProcesses -Behavior 'Fail'

    $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
    Write-Debug "Exit code returned from Start-VSChocolateyProcessAsAdmin: '$exitCode'"
    if ($assumeNewVS2017Installer)
    {
        $auxExitCode = Wait-VSInstallerProcesses -Behavior 'Wait'
        if ($auxExitCode -ne $null -and $exitCode -eq 0)
        {
            Write-Debug "Using aux exit code returned from Wait-VSInstallerProcesses ('$auxExitCode')"
            $exitCode = $auxExitCode
        }
    }
    Write-Debug "Setting Env:ChocolateyExitCode to '$exitCode'"
    $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 Windows!@!.
            # [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\Get-VSWebFile.ps1
# based on Install-ChocolateyPackage (a9519b5), with changes:
# - 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)
function Get-VSWebFile
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)] [string] $PackageName,
        [Parameter(Mandatory = $true)] [string] $DefaultFileName,
        [Parameter(Mandatory = $true)] [string] $FileDescription,
        [string] $Url,
        [alias("Url64")][string] $Url64Bit = '',
        [string] $Checksum = '',
        [string] $ChecksumType = '',
        [string] $Checksum64 = '',
        [string] $ChecksumType64 = '',
        [string] $LocalFilePath,
        [hashtable] $Options
    )

    Write-Debug "Running 'Get-VSWebFile' for $PackageName with Url:'$Url', Url64Bit:'$Url64Bit', Checksum:'$Checksum', ChecksumType:'$ChecksumType', Checksum64:'$Checksum64', ChecksumType64:'$ChecksumType64', LocalFilePath:'$LocalFilePath'";

    if ($LocalFilePath -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 -match '\.((exe)|(vsix))$') { $localFileName = $urlForFileNameDetermination.Substring($urlForFileNameDetermination.LastIndexOfAny(@('/', '\')) + 1) }
        else { $localFileName = $DefaultFileName }
        $LocalFilePath = Join-Path $tempDir $localFileName

        Write-Verbose "Downloading the $FileDescription"
        $arguments = @{
            PackageName = $PackageName
            FileFullPath = $LocalFilePath
            Url = $Url
            Url64Bit = $Url64Bit
            Checksum = $Checksum
            ChecksumType = $ChecksumType
            Checksum64 = $Checksum64
            ChecksumType64 = $ChecksumType64
        }

        $gcwf = Get-Command -Name Get-ChocolateyWebFile
        if ($gcwf.Parameters.ContainsKey('Options'))
        {
            $arguments.Options = $Options
        }
        else
        {
            if ($Options -ne $null -and $Options.Keys.Count -gt 0)
            {
                Write-Warning "This Chocolatey version does not support passing custom Options to Get-ChocolateyWebFile."
            }
        }

        Set-StrictMode -Off
        Get-ChocolateyWebFile @arguments | Out-Null
        Set-StrictMode -Version 2
    } else {
        if (-not (Test-Path -Path $LocalFilePath)) {
            throw "The local $FileDescription does not exist: $LocalFilePath"
        }
        Write-Verbose "Using a local ${FileDescription}: $LocalFilePath"
    }

    return $LocalFilePath
}
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-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-VSRequiredInstallerVersion.ps1
function Get-VSRequiredInstallerVersion
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [hashtable] $PackageParameters,
        [PSObject] $ChannelReference,
        [switch] $UseInstallChannelUri
    )
    Write-Verbose 'Trying to determine the required installer and engine version from the manifests'

    Write-Debug 'Obtaining the channel manifest in order to determine the required installer version'
    $channelManifest = Get-VSChannelManifest -PackageParameters $PackageParameters -ChannelReference $ChannelReference -UseInstallChannelUri:$UseInstallChannelUri

    Write-Debug 'Parsing the channel manifest'
    $version = $null
    $channelItem = Get-VSChannelManifestItem -Manifest $channelManifest -ChannelItemType 'Bootstrapper'
    if ($channelItem -is [Collections.IDictionary] -and $channelItem.ContainsKey('version'))
    {
        $versionString = $channelItem['version']
        if ($versionString -is [string])
        {
            try
            {
                $version = [version]$versionString
            }
            catch
            {
                Write-Debug ('Manifest parsing error: failed to parse version string ''{0}''' -f $versionString)
            }
        }
        else
        {
            Write-Debug 'Manifest parsing error: version is not a string'
        }
    }
    else
    {
        Write-Debug 'Manifest parsing error: channelItem is not IDictionary or does not contain version'
    }

    if ($version -ne $null)
    {
        Write-Verbose "Required installer version determined from the channel manifest: '$version'"
    }
    else
    {
        Write-Verbose "The required installer version could not be determined from the component manifest"
    }

    Write-Debug 'Obtaining the component manifest in order to determine the required engine version'
    $manifest = Get-VSComponentManifest -PackageParameters $PackageParameters -ChannelReference $ChannelReference -ChannelManifest $channelManifest -UseInstallChannelUri:$UseInstallChannelUri

    Write-Debug 'Parsing the component manifest'
    $engineVersion = $null
    if ($manifest -is [Collections.IDictionary] -and $manifest.ContainsKey('engineVersion'))
    {
        $engineVersionString = $manifest['engineVersion']
        if ($engineVersionString -is [string])
        {
            $engineVersion = [version]$engineVersionString
        }
        else
        {
            Write-Debug 'Manifest parsing error: engineVersion is not a string'
        }
    }
    else
    {
        Write-Debug 'Manifest parsing error: manifest is not IDictionary or does not contain engineVersion'
    }

    if ($engineVersion -ne $null)
    {
        Write-Verbose "Required engine version determined from the component manifest: '$engineVersion'"
    }
    else
    {
        Write-Verbose "The required engine version could not be determined from the component manifest"
    }

    $props = @{
        Version = $version
        EngineVersion = $engineVersion
    }
    $obj = New-Object -TypeName PSObject -Property $props
    Write-Output $obj
}
extensions\Get-VSProductReference.ps1
function Get-VSProductReference
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [PSObject] $ChannelReference,
        [Parameter(Mandatory = $true)] [string] $Product
    )

    $productId = "Microsoft.VisualStudio.Product." + $Product
    $obj = New-VSProductReference -ChannelId $ChannelReference.ChannelId -ProductId $productId
    return $obj
}
extensions\Get-VSManifest.ps1
function Get-VSManifest
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [string] $Description,
        [Parameter(Mandatory = $true)] [string] $Url,
        [string] $LayoutFileName,
        [string] $LayoutPath
    )

    Write-Verbose "Obtaining the manifest file for url '$Url' ($Description)"
    $chocTempDir = $env:TEMP
    $tempDir = Join-Path $chocTempDir 'chocolatey-visualstudio.extension'
    if (![System.IO.Directory]::Exists($tempDir)) { [System.IO.Directory]::CreateDirectory($tempDir) | Out-Null }

    if (-not [string]::IsNullOrEmpty($LayoutFileName))
    {
        $localFilePrefix = [IO.Path]::GetFileNameWithoutExtension($LayoutFileName) + '_'
    }
    else
    {
        $localFilePrefix = ''
    }

    $localFileName = '{0}{1}.man' -f $localFilePrefix, $Url.GetHashCode()
    $localFilePath = Join-Path $tempDir $localFileName

    $localFile = Get-Item -Path $localFilePath -ErrorAction SilentlyContinue
    if ($localFile -ne $null -and (Get-Date).ToUniversalTime().AddDays(-1) -lt $localFile.LastWriteTimeUtc -and $localFile.LastWriteTimeUtc -lt (Get-Date).ToUniversalTime())
    {
        Write-Verbose ("Found cached file '{0}' last updated on {1:yyyy-MM-dd HH:mm:ss} UTC - less than one day ago (now is {2:yyyy-MM-dd HH:mm:ss} UTC)" -f $localFilePath, $localFile.LastWriteTimeUtc, (Get-Date).ToUniversalTime())
    }
    else
    {
        if ($localFile -eq $null)
        {
            Write-Verbose ("Local cached file '{0}' does not exist" -f $localFilePath)
        }
        else
        {
            Write-Verbose ("Found cached file '{0}' last updated on {1:yyyy-MM-dd HH:mm:ss} UTC which is outside the allowed 1-day window (now is {2:yyyy-MM-dd HH:mm:ss} UTC)" -f $localFilePath, $localFile.LastWriteTimeUtc, (Get-Date).ToUniversalTime())
            Remove-Item -Path $localFile
        }

        $fileInLayout = $null
        if ($LayoutPath -ne '' -and $LayoutFileName -ne '')
        {
            $fileInLayout = Join-Path -Path $LayoutPath -ChildPath $LayoutFileName
        }

        if ($fileInLayout -ne $null)
        {
            Write-Verbose "Found the manifest file in the layout: '$fileInLayout'"
            Copy-Item -Path $fileInLayout -Destination $localFilePath
        }
        else
        {
            Write-Verbose "Downloading the manifest file ($Description)"
            $arguments = @{
                packageName = $Description
                fileFullPath = $localFilePath
                url = $Url
            }

            Set-StrictMode -Off
            try
            {
                Get-ChocolateyWebFile @arguments | Out-Null
            }
            catch
            {
                if (Test-Path -Path $localFilePath)
                {
                    Write-Debug 'Download failed, removing the local file'
                    Remove-Item -Path $localFilePath -ErrorAction SilentlyContinue
                }

                throw
            }
            finally
            {
                Set-StrictMode -Version 2
            }
        }
    }

    Write-Verbose "Reading the manifest file ($Description)"
    $manifestContent = [System.IO.File]::ReadAllText($localFilePath)

    # VS 2017 requires Windows 7 or later, so .NET 3.5 or later is guaranteed, therefore we can use System.Web.Extensions
    [System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions") | Out-Null
    $serializer = New-Object -TypeName 'System.Web.Script.Serialization.JavaScriptSerializer'
    $serializer.MaxJsonLength = [int]::MaxValue
    Write-Verbose "Parsing the manifest file ($Description)"
    $manifest = $serializer.DeserializeObject($manifestContent)

    return $manifest
}
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-VSComponentManifest.ps1
function Get-VSComponentManifest
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [hashtable] $PackageParameters,
        [PSObject] $ChannelReference,
        [System.Collections.IDictionary] $ChannelManifest,
        [switch] $UseInstallChannelUri
    )

    # look in LayoutPath only if --noWeb
    if (-not $packageParameters.ContainsKey('noWeb'))
    {
        Write-Debug 'Not looking in LayoutPath because --noWeb was not passed in package parameters'
        $layoutPath = $null
    }
    else
    {
        $layoutPath = Resolve-VSLayoutPath -PackageParameters $PackageParameters
    }

    if ($ChannelManifest -eq $null)
    {
        Write-Debug 'Obtaining the channel manifest'
        $ChannelManifest = Get-VSChannelManifest -PackageParameters $PackageParameters -ChannelReference $ChannelReference -LayoutPath $layoutPath -UseInstallChannelUri:$UseInstallChannelUri
    }

    Write-Debug 'Parsing the channel manifest'
    $url, $checksum, $checksumType = Get-VSChannelManifestItemUrl -Manifest $ChannelManifest -ChannelItemType 'Manifest'

    if ($url -eq $null)
    {
        Write-Verbose 'Unable to determine the catalog manifest url'
        return $null
    }

    # -Checksum and -ChecksumType are not passed, because the info from the channel manifest seems bogus - does not match reality
    $catalogManifest = Get-VSManifest -Description 'catalog manifest' -Url $url -LayoutFileName 'Catalog.json' -LayoutPath $layoutPath

    return $catalogManifest
}
extensions\Get-VSChannelUri.ps1
function Get-VSChannelUri
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [string] $ChannelId
    )

    $manifestUri = $null
    $success = $ChannelId -match '^VisualStudio\.(?<version>\d+)\.(?<kind>\w+)$' # VisualStudio.15.Release
    if ($success)
    {
        $kind = switch ($Matches['kind'])
        {
            'Preview' { 'pre' }
            default { $_.ToLowerInvariant() }
        }

        $manifestUri = 'https://aka.ms/vs/{0}/{1}/channel' -f $Matches['version'], $kind
        Write-Debug "Using channel manifest URI computed from the channel id: '$manifestUri'"
    }
    else
    {
        Write-Error "Channel id '$ChannelId' does not match the expected pattern and cannot be used to compute the channel manifest URI"
    }

    return $manifestUri
}
extensions\Get-VSChannelReference.ps1
function Get-VSChannelReference
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [ValidateSet('2017', '2019')] [string] $VisualStudioYear,
        [bool] $Preview
    )

    switch ($VisualStudioYear)
    {
        '2017' { $majorVersion = 15 }
        '2019' { $majorVersion = 16 }
        default { throw "Unsupported VisualStudioYear: $VisualStudioYear"}
    }

    $mapPreviewOrReleaseToChannelTypeSuffix = @{ $true = 'Preview'; $false = 'Release' }
    $channelId = 'VisualStudio.{0}.{1}' -f $majorVersion, $mapPreviewOrReleaseToChannelTypeSuffix[$Preview]

    $obj = New-VSChannelReference -ChannelId $channelId
    return $obj
}
extensions\Get-VSChannelManifestItemUrl.ps1
function Get-VSChannelManifestItemUrl
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [System.Collections.IDictionary] $Manifest,
        [ValidateSet('Bootstrapper', 'Manifest')] [Parameter(Mandatory = $true)] [string] $ChannelItemType
    )

    $url = $null
    $checksum = $null
    $checksumType = $null
    $channelItem = Get-VSChannelManifestItem -Manifest $Manifest -ChannelItemType $ChannelItemType
    if ($channelItem -is [Collections.IDictionary] -and $channelItem.ContainsKey('payloads'))
    {
        $payloads = $channelItem['payloads']
        if ($payloads -is [array])
        {
            if (($payloads | Measure-Object).Count -eq 1)
            {
                $payload = $payloads[0]
                if ($payload -is [Collections.IDictionary] -and $payload.ContainsKey('url'))
                {
                    $url = $payload['url']
                    if (-not [string]::IsNullOrEmpty($url) -and $payload.ContainsKey('sha256'))
                    {
                        $checksum = $payload['sha256']
                        $checksumType = 'sha256'
                    }
                    else
                    {
                        Write-Debug 'Manifest parsing error: payload url is empty or payload does not contain sha256'
                        # url will still be returned; it might be useful even without the checksum
                    }
                }
                else
                {
                    Write-Debug 'Manifest parsing error: payload is not IDictionary or does not contain url'
                }
            }
            else
            {
                Write-Debug 'Manifest parsing error: zero or more than one payload objects found'
            }
        }
        else
        {
            Write-Debug 'Manifest parsing error: payloads is not an array'
        }
    }
    else
    {
        Write-Debug 'Manifest parsing error: channelItem is not IDictionary or does not contain payloads'
    }

    if (-not [string]::IsNullOrEmpty($url))
    {
        Write-Verbose "$ChannelItemType url determined from the channel manifest: '$url' (checksum: '$checksum', type: '$checksumType')"
        return $url, $checksum, $checksumType
    }
    else
    {
        Write-Verbose "The $ChannelItemType url could not be determined from the channel manifest"
        return $null
    }
}
extensions\Get-VSChannelManifestItem.ps1
function Get-VSChannelManifestItem
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [System.Collections.IDictionary] $Manifest,
        [ValidateSet('Bootstrapper', 'Manifest')] [Parameter(Mandatory = $true)] [string] $ChannelItemType
    )

    $result = $null
    if ($Manifest -is [Collections.IDictionary] -and $Manifest.ContainsKey('channelItems'))
    {
        $channelItems = $Manifest['channelItems']
        if ($channelItems -is [array])
        {
            $channelItem = $channelItems | Where-Object { $_ -is [Collections.IDictionary] -and $_.ContainsKey('type') -and $_['type'] -eq $ChannelItemType }
            if (($channelItem | Measure-Object).Count -eq 1)
            {
                if ($channelItem -is [Collections.IDictionary])
                {
                    $result = $channelItem
                }
                else
                {
                    Write-Debug 'Manifest parsing error: channelItem is not IDictionary'
                }
            }
            else
            {
                Write-Debug 'Manifest parsing error: zero or more than one channelItem objects found'
            }
        }
        else
        {
            Write-Debug 'Manifest parsing error: channelItems is not an array'
        }
    }
    else
    {
        Write-Debug 'Manifest parsing error: manifest is not IDictionary or does not contain channelItems'
    }

    if ($result -ne $null)
    {
        Write-Debug "Located channel manifest item of type $ChannelItemType"
    }
    else
    {
        Write-Debug "Could not locate the channel manifest item of type $ChannelItemType"
    }

    return $result
}
extensions\Get-VSChannelManifest.ps1
function Get-VSChannelManifest
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [hashtable] $PackageParameters,
        [PSObject] $ChannelReference,
        [switch] $UseInstallChannelUri,
        [string] $LayoutPath
    )

    $manifestUri = $null
    # first, see if the caller provided the manifest uri via package parameters or ChannelReference
    Write-Debug 'Checking if the channel manifest URI has been provided'
    Write-Debug ('InstallChannelUri will {0}' -f @{ $true = 'be used, if present'; $false = 'not be used' }[[bool]$UseInstallChannelUri])
    if ($UseInstallChannelUri -and $PackageParameters.ContainsKey('installChannelUri') -and -not [string]::IsNullOrEmpty($PackageParameters['installChannelUri']))
    {
        $manifestUri = $PackageParameters['installChannelUri']
        Write-Debug "Using channel manifest URI from the 'installChannelUri' package parameter: '$manifestUri'"
    }
    else
    {
        Write-Debug "Package parameters do not contain 'installChannelUri', it is empty or the scenario does not allow its use"
        if ($PackageParameters.ContainsKey('channelUri') -and -not [string]::IsNullOrEmpty($PackageParameters['channelUri']))
        {
            $manifestUri = $PackageParameters['channelUri']
            Write-Debug "Using channel manifest URI from the 'channelUri' package parameter: '$manifestUri'"
        }
        else
        {
            Write-Debug "Package parameters do not contain 'channelUri' or it is empty"
            if ($ChannelReference -ne $null)
            {
                if ($UseInstallChannelUri -and -not [string]::IsNullOrEmpty($ChannelReference.InstallChannelUri))
                {
                    $manifestUri = $ChannelReference.InstallChannelUri
                    Write-Debug "Using manifest URI from the InstallChannelUri property of the provided ChannelReference: '$manifestUri'"
                }
                else
                {
                    Write-Debug "ChannelReference InstallChannelUri property is empty"
                    if (-not [string]::IsNullOrEmpty($ChannelReference.ChannelUri))
                    {
                        $manifestUri = $ChannelReference.ChannelUri
                        Write-Debug "Using manifest URI from the ChannelUri property of the provided ChannelReference: '$manifestUri'"
                    }
                    else
                    {
                        Write-Debug "ChannelReference ChannelUri property is empty"
                    }
                }
            }
            else
            {
                Write-Debug "ChannelReference has not been provided"
            }
        }
    }

    if ($manifestUri -eq $null)
    {
        # second, try to compute the uri from the channel id
        Write-Debug 'Checking if the channel id has been provided'
        $channelId = $null
        if ($PackageParameters.ContainsKey('channelId') -and -not [string]::IsNullOrEmpty($PackageParameters['channelId']))
        {
            $channelId = $PackageParameters['channelId']
            Write-Debug "Using channel id from the 'channelId' package parameter: '$channelId'"
        }
        else
        {
            Write-Debug "Package parameters do not contain 'channelId' or it is empty"
            if ($ChannelReference -ne $null)
            {
                $channelId = $ChannelReference.ChannelId
                Write-Debug "Using channel id from the provided ChannelReference: '$channelId'"
            }
            else
            {
                Write-Debug "ChannelReference has not been provided; channel id is not known"
            }
        }
        if ($channelId -ne $null)
        {
            $manifestUri = Get-VSChannelUri -ChannelId $channelId -ErrorAction SilentlyContinue
        }
    }

    if ($manifestUri -eq $null)
    {
        # Finally, fall back to hardcoded.
        # This may currently happen only when Install-VisualStudio is called without -VisualStudioVersion and -Product (which are not mandatory for backward compat with old package versions).
        # Ultimately, code should be reworked to make ChannelReference mandatory in this function and eliminate this hardcoded value.
        $manifestUri = 'https://aka.ms/vs/15/release/channel'
        Write-Warning "Fallback: using hardcoded channel manifest URI: '$manifestUri'"
    }

    if ($LayoutPath -eq '')
    {
        # look in LayoutPath only if --noWeb
        if (-not $packageParameters.ContainsKey('noWeb'))
        {
            Write-Debug 'Not looking in LayoutPath because --noWeb was not passed in package parameters'
        }
        else
        {
            $LayoutPath = Resolve-VSLayoutPath -PackageParameters $PackageParameters
        }
    }
    else
    {
        Write-Debug "Using provided LayoutPath: $LayoutPath"
    }

    $manifest = Get-VSManifest -Description 'channel manifest' -Url $manifestUri -LayoutFileName 'ChannelManifest.json' -LayoutPath $LayoutPath

    return $manifest
}
extensions\Get-VSBootstrapperUrlFromChannelManifest.ps1
function Get-VSBootstrapperUrlFromChannelManifest
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [hashtable] $PackageParameters,
        [PSObject] $ChannelReference,
        [switch] $UseInstallChannelUri
    )
    Write-Verbose 'Trying to determine the bootstrapper (vs_Setup.exe) url from the channel manifest'

    Write-Debug 'Obtaining the channel manifest'
    $manifest = Get-VSChannelManifest -PackageParameters $PackageParameters -ChannelReference $ChannelReference -UseInstallChannelUri:$UseInstallChannelUri

    Write-Debug 'Parsing the channel manifest'
    $url, $checksum, $checksumType = Get-VSChannelManifestItemUrl -Manifest $manifest -ChannelItemType 'Bootstrapper'

    return $url, $checksum, $checksumType
}
extensions\Get-VisualStudioVsixInstaller.ps1
function Get-VisualStudioVsixInstaller
{
<#
.SYNOPSIS
Locates the Visual Studio extension (VSIX) installer.

.DESCRIPTION
Locates all instances of the Visual Studio extension installer
(VSIXInstaller.exe) present on the machine and returns their
paths and version numbers.

.PARAMETER Latest
Returns the VSIXInstaller.exe with the highest version number only.

.OUTPUTS
For each VSIXInstaller.exe instance found, returns an object
containing these properties:
Path - the path to the VSIXInstaller.exe instance.
Version - the program version number, extracted from the ProductVersion
          property of the version resource embedded in the program.

.NOTES
Supports both VS 2017+ and "legacy" VS versions (2015 and earlier).
#>
    [CmdletBinding()]
    Param
    (
        [switch] $Latest
    )
    Write-Debug "Running 'Get-VisualStudioVsixInstaller' with Latest:'$Latest'";

    $candidates = New-Object System.Collections.ArrayList
    $modernProducts = Get-WillowInstalledProducts
    $modernProducts `
        | Where-Object { $_ -ne $null } `
        | ForEach-Object { $_['enginePath'] } `
        | Where-Object { -not [string]::IsNullOrEmpty($_) } `
        | Select-Object -Unique `
        | ForEach-Object { Get-Item -Path "$_\VSIXInstaller.exe" -ErrorAction SilentlyContinue } `
        | ForEach-Object { [void]$candidates.Add($_) }

    if (-not $Latest -or $candidates.Count -eq 0)
    {
        $legacyProducts = Get-VSLegacyInstance
        $legacyProducts `
            | Where-Object { $_ -ne $null } `
            | Select-Object -ExpandProperty Path -Unique `
            | Where-Object { -not [string]::IsNullOrEmpty($_) } `
            | ForEach-Object { Get-Item -Path "$_\Common7\IDE\VSIXInstaller.exe" -ErrorAction SilentlyContinue } `
            | ForEach-Object { [void]$candidates.Add($_) }
    }
    else
    {
        Write-Debug 'Not looking for VSIXInstaller in legacy VS products because -Latest was specified and more modern VS product(s) were found.'
    }

    $rxVersion = [regex]'^\d+(\.\d+)+'
    $sortedCandidates = $candidates `
        | Select-Object -Property `
            @{ Name = 'Path'; Expression = { $_.FullName } }, 
            @{ Name = 'Version'; Expression = { [version]($rxVersion.Match($_.VersionInfo.ProductVersion).Value) } } `
        | Sort-Object -Property Version -Descending `
        | ForEach-Object { Write-Debug ('Found VSIXInstaller.exe version ''{0}'': {1}' -f $_.Version, $_.Path); $_ }

    if ($Latest)
    {
        if (($sortedCandidates | Measure-Object).Count -eq 0)
        {
            Write-Error 'The VSIX Installer is not present.'
        }
        else
        {
            Write-Output ($sortedCandidates[0])
        }
    }
    else
    {
        $sortedCandidates | Write-Output
    }
}
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,
        [bool] $Preview
    )
    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' Preview:'$Preview'";
    $argumentList = @('remove', "$Component")

    $channelReference = Get-VSChannelReference -VisualStudioYear $VisualStudioYear -Preview $Preview
    Start-VSModifyOperation -PackageName $PackageName -ArgumentList $argumentList -ChannelReference $channelReference -ApplicableProducts $ApplicableProducts -OperationTexts @('uninstalled', 'uninstalling', 'uninstallation')
}
extensions\New-VSChannelReference.ps1
function New-VSChannelReference
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [string] $ChannelId,
        [string] $ChannelUri,
        [string] $InstallChannelUri
    )

    $props = @{
        ChannelId = $ChannelId
        ChannelUri = $ChannelUri
        InstallChannelUri = $InstallChannelUri
    }

    $obj = New-Object -TypeName PSObject -Property $props
    return $obj
}
extensions\Merge-AdditionalArguments.ps1
function Merge-AdditionalArguments
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [hashtable] $Arguments,
        [Parameter(Mandatory = $true)] [hashtable] $AdditionalArguments
    )

    foreach ($kvp in $AdditionalArguments.GetEnumerator())
    {
        $val = $kvp.Value
        if ($val -ne $null)
        {
            # strip quotes; will be added later, if needed
            if ($val -is [string])
            {
                $val = $val.Trim('''" ')
            }
            else
            {
                if ($val -is [System.Collections.IList])
                {
                    $newList = New-Object -TypeName System.Collections.ArrayList
                    foreach ($oneVal in $val)
                    {
                        if ($oneVal -is [string])
                        {
                            $oneVal = $oneVal.Trim('''" ')
                        }

                        [void]$newList.Add($oneVal)
                    }

                    $val = $newList
                }
            }
        }

        if ($Arguments.ContainsKey($kvp.Key) -and $Arguments[$kvp.Key] -ne $val)
        {
            Write-Debug "Replacing argument '$($kvp.Key)' value '$($Arguments[$kvp.Key])' with '$val'"
        }

        $Arguments[$kvp.Key] = $val
    }
}
extensions\Install-VSInstaller.ps1
function Install-VSInstaller
{
    [CmdletBinding()]
    param(
      [Parameter(Mandatory = $true)] [string] $PackageName,
      [Parameter(Mandatory = $true)] [hashtable] $PackageParameters,
      [PSObject] $ChannelReference,
      [string] $Url,
      [string] $Checksum,
      [string] $ChecksumType,
      [Alias('RequiredVersion')] [version] $RequiredInstallerVersion,
      [version] $RequiredEngineVersion,
      [switch] $Force,
      [switch] $UseInstallChannelUri
    )
    Write-Debug "Running 'Install-VSInstaller' for $PackageName with Url:'$Url' Checksum:$Checksum ChecksumType:$ChecksumType RequiredInstallerVersion:'$RequiredInstallerVersion' RequiredEngineVersion:'$RequiredEngineVersion' Force:'$Force' UseInstallChannelUri:'$UseInstallChannelUri'";
    $argumentSet = $PackageParameters.Clone()

    Write-Debug 'Determining whether the Visual Studio Installer needs to be installed/updated/reinstalled'
    $shouldUpdate = $false
    $existing = Get-VisualStudioInstaller
    if ($existing -ne $null)
    {
        Write-Debug 'The Visual Studio Installer is already present'
        if ($existing.Version -ne $null -and $RequiredInstallerVersion -ne $null)
        {
            if ($existing.Version -lt $RequiredInstallerVersion)
            {
                Write-Debug 'The existing Visual Studio Installer version is lower than requested, so it should be updated'
                $shouldUpdate = $true
            }
            elseif ($existing.Version -eq $RequiredInstallerVersion)
            {
                Write-Debug 'The existing Visual Studio Installer version is equal to requested (no update required)'
            }
            else
            {
                Write-Debug 'The existing Visual Studio Installer version is greater than requested (no update required)'
            }
        }

        if ($existing.EngineVersion -ne $null -and $RequiredEngineVersion -ne $null)
        {
            if ($existing.EngineVersion -lt $RequiredEngineVersion)
            {
                Write-Debug 'The existing Visual Studio Installer engine version is lower than requested, so it should be updated'
                $shouldUpdate = $true
            }
            elseif ($existing.EngineVersion -eq $RequiredEngineVersion)
            {
                Write-Debug 'The existing Visual Studio Installer engine version is equal to requested (no update required)'
            }
            else
            {
                Write-Debug 'The existing Visual Studio Installer engine version is greater than requested (no update required)'
            }
        }
    }
    else
    {
        Write-Debug 'The Visual Studio Installer is not present and will be installed'
        $shouldUpdate = $true
    }

    $attemptingRepair = $false
    if (-not $shouldUpdate)
    {
        $existingHealth = $existing | Get-VisualStudioInstallerHealth
        if ($existingHealth -ne $null -and -not $existingHealth.IsHealthy)
        {
            Write-Warning "The Visual Studio Installer is broken (missing files: $($existingHealth.MissingFiles -join ', ')). Attempting to reinstall it."
            $shouldUpdate = $true
            $attemptingRepair = $true
        }
    }

    if (-not $shouldUpdate -and $Force)
    {
        Write-Debug 'The Visual Studio Installer does not need to be updated, but it will be reinstalled because -Force was used'
        $shouldUpdate = $true
    }

    if (-not $shouldUpdate)
    {
        return
    }

    # if installing from layout, check for existence of vs_installer.opc and auto add --offline
    if (-not $argumentSet.ContainsKey('offline'))
    {
        $layoutPath = Resolve-VSLayoutPath -PackageParameters $argumentSet
        if ($layoutPath -ne $null)
        {
            $installerOpcPath = Join-Path -Path $layoutPath -ChildPath 'vs_installer.opc'
            if (Test-Path -Path $installerOpcPath)
            {
                Write-Debug "The VS Installer package is present in the layout path: $installerOpcPath"
                # TODO: also if the version in layout will satisfy version requirements
                if ($argumentSet.ContainsKey('noWeb'))
                {
                    Write-Debug "Using the VS Installer package present in the layout path because --noWeb was passed in package parameters"
                    $argumentSet['offline'] = $installerOpcPath
                }
                else
                {
                    Write-Debug "Not using the VS Installer package present in the layout path because --noWeb was not passed in package parameters"
                }
            }
        }
    }

    if ($argumentSet.ContainsKey('bootstrapperPath'))
    {
        $installerFilePath = $argumentSet['bootstrapperPath']
        $argumentSet.Remove('bootstrapperPath')
        Write-Debug "User-provided bootstrapper path: $installerFilePath"
    }
    else
    {
        $installerFilePath = $null
        if ($Url -eq '')
        {
            $Url, $Checksum, $ChecksumType = Get-VSBootstrapperUrlFromChannelManifest -PackageParameters $argumentSet -ChannelReference $ChannelReference -UseInstallChannelUri:$UseInstallChannelUri
        }
    }

    $downloadedOrProvidedExe = Get-VSWebFile `
        -PackageName 'Visual Studio Installer' `
        -DefaultFileName 'vs_setup.exe' `
        -FileDescription 'installer executable' `
        -Url $Url `
        -Checksum $Checksum `
        -ChecksumType $ChecksumType `
        -LocalFilePath $installerFilePath

    $isBox = (Split-Path -Leaf -Path $downloadedOrProvidedExe) -ne 'vs_setup_bootstrapper.exe' # in case the user pointed us to already extracted vs_setup_bootstrapper.exe
    if ($isBox)
    {
        # vs_Setup.exe 15.6 has a flaw in its handling of --quiet --update:
        # because vs_Setup.exe appends an additional argument (--env) to vs_setup_bootstrapper.exe,
        # the latter thinks it is in "roundtrip update" and starts vs_installer.exe at the end.
        # This flaw is not present in vs_Setup.exe 15.7 or later, presumably because of improved
        # parameter handling in vs_setup_bootstrapper.exe.
        Write-Debug 'Checking the version of the box executable'
        $boxVersion = [version](Get-Item -Path $downloadedOrProvidedExe).VersionInfo.FileVersion
        $shouldUnpackBox = [version]'15.6' -le $boxVersion -and $boxVersion -lt [version]'15.7'
        if ($shouldUnpackBox)
        {
            Write-Debug "The box executable (version $boxVersion) is affected by the --quiet --update flaw, so it will be unpacked as a workaround"

            $chocTempDir = $env:TEMP
            $tempDir = Join-Path $chocTempDir "$PackageName"
            if ($env:packageVersion -ne $null) { $tempDir = Join-Path $tempDir "$env:packageVersion" }

            $extractedBoxPath = Join-Path -Path $tempDir -ChildPath (Get-Item -Path $downloadedOrProvidedExe).BaseName
            if (Test-Path -Path $extractedBoxPath)
            {
                Write-Debug "Removing already existing box extraction path: $extractedBoxPath"
                Remove-Item -Path $extractedBoxPath -Recurse
            }

            Get-ChocolateyUnzip `
                -PackageName 'Visual Studio Installer' `
                -FileFullPath $downloadedOrProvidedExe `
                -Destination $extractedBoxPath `
                | Out-Null

            $vsSetupBootstrapperExe = Join-Path -Resolve -Path $extractedBoxPath -ChildPath 'vs_bootstrapper_d15\vs_setup_bootstrapper.exe'
            $installerToRun = $vsSetupBootstrapperExe
        }
        else
        {
            Write-Debug "The box executable (version $boxVersion) is not affected by the --quiet --update flaw, so it will be used directly"
            $installerToRun = $downloadedOrProvidedExe
        }
    }
    else
    {
        Write-Debug "It looks like the provided bootstrapperPath points to an already extracted vs_setup_bootstrapper.exe"
        $installerToRun = $downloadedOrProvidedExe
    }

    $whitelist = @('quiet', 'offline')
    Remove-VSPackageParametersNotPassedToNativeInstaller -PackageParameters $argumentSet -TargetDescription 'bootstrapper during VS Installer update' -Whitelist $whitelist

    # --update must be last
    $argumentSet['quiet'] = $null
    $silentArgs = ConvertTo-ArgumentString -Arguments $argumentSet -FinalUnstructuredArguments @('--update') -Syntax 'Willow'
    $arguments = @{
        packageName = 'Visual Studio Installer'
        silentArgs = $silentArgs
        file = $installerToRun
        logFilePath = $null
        assumeNewVS2017Installer = $true
    }
    $argumentsDump = ($arguments.GetEnumerator() | ForEach-Object { '-{0}:''{1}''' -f $_.Key,"$($_.Value)" }) -join ' '

    $attempt = 0
    do
    {
        $retry = $false
        $attempt += 1
        Write-Debug "Install-VSChocolateyInstallPackage $argumentsDump"
        Install-VSChocolateyInstallPackage @arguments

        $updated = Get-VisualStudioInstaller
        if ($updated -eq $null)
        {
            throw 'The Visual Studio Installer is not present even after supposedly successful update!'
        }

        if ($existing -eq $null)
        {
            Write-Verbose "The Visual Studio Installer version $($updated.Version) (engine version $($updated.EngineVersion)) was installed."
        }
        else
        {
            if ($updated.Version -eq $existing.Version -and $updated.EngineVersion -eq $existing.EngineVersion)
            {
                Write-Verbose "The Visual Studio Installer version $($updated.Version) (engine version $($updated.EngineVersion)) was reinstalled."
            }
            else
            {
                if ($updated.Version -lt $existing.Version)
                {
                    Write-Warning "The Visual Studio Installer got updated, but its version after update ($($updated.Version)) is lower than the version before update ($($existing.Version))."
                }
                else
                {
                    if ($updated.EngineVersion -lt $existing.EngineVersion)
                    {
                        Write-Warning "The Visual Studio Installer got updated, but its engine version after update ($($updated.EngineVersion)) is lower than the engine version before update ($($existing.EngineVersion))."
                    }
                    else
                    {
                        Write-Verbose "The Visual Studio Installer got updated to version $($updated.Version) (engine version $($updated.EngineVersion))."
                    }
                }
            }
        }

        if ($updated.Version -ne $null)
        {
            if ($RequiredInstallerVersion -ne $null)
            {
                if ($updated.Version -lt $RequiredInstallerVersion)
                {
                    Write-Warning "The Visual Studio Installer got updated to version $($updated.Version), which is still lower than the requirement of version $RequiredInstallerVersion or later."
                }
                else
                {
                    Write-Verbose "The Visual Studio Installer got updated to version $($updated.Version), which satisfies the requirement of version $RequiredInstallerVersion or later."
                }
            }
        }
        else
        {
            Write-Warning "Unable to determine the Visual Studio Installer version after the update."
        }

        if ($updated.EngineVersion -ne $null)
        {
            if ($RequiredEngineVersion -ne $null)
            {
                if ($updated.EngineVersion -lt $RequiredEngineVersion)
                {
                    Write-Warning "The Visual Studio Installer engine got updated to version $($updated.EngineVersion), which is still lower than the requirement of version $RequiredEngineVersion or later."
                }
                else
                {
                    Write-Verbose "The Visual Studio Installer engine got updated to version $($updated.EngineVersion), which satisfies the requirement of version $RequiredEngineVersion or later."
                }
            }
        }
        else
        {
            Write-Warning "Unable to determine the Visual Studio Installer engine version after the update."
        }

        $updatedHealth = $updated | Get-VisualStudioInstallerHealth
        if (-not $updatedHealth.IsHealthy)
        {
            if ($attempt -eq 1)
            {
                if ($attemptingRepair)
                {
                    $msg = 'is still broken after reinstall'
                }
                else
                {
                    $msg = 'got broken after update'
                }

                Write-Warning "The Visual Studio Installer $msg (missing files: $($updatedHealth.MissingFiles -join ', ')). Attempting to repair it."
                $installerDir = Split-Path -Path $updated.Path
                $newName = '{0}.backup-{1:yyyyMMddHHmmss}' -f (Split-Path -Leaf -Path $installerDir), (Get-Date)
                Write-Verbose "Renaming directory '$installerDir' to '$newName'"
                Rename-Item -Path $installerDir -NewName $newName
                Write-Verbose 'Retrying the installation'
                $retry = $true
            }
            else
            {
                throw "The Visual Studio Installer is still broken even after the attempt to repair it."
            }
        }
        else
        {
            Write-Verbose 'The Visual Studio Installer is healthy (no missing files).'
        }
    }
    while ($retry)
}
extensions\Install-VSChocolateyPackage.ps1
# based on Install-ChocolateyPackage (a9519b5), with changes:
# - added recognition of exit codes signifying reboot requirement
# - VS installers are exe
# - removed exit code parameters in order to centralize exit code logic
# - download logic refactored into a separate function for reuse
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'";

    $localFilePath = Get-VSWebFile `
        -PackageName $PackageName `
        -DefaultFileName 'vs_setup.exe' `
        -FileDescription 'installer executable' `
        -Url $url `
        -Url64Bit $url64bit `
        -Checksum $checksum `
        -ChecksumType $checksumType `
        -Checksum64 $checksum64 `
        -ChecksumType64 $checksumType64 `
        -LocalFilePath $installerFilePath

    $arguments = @{
        packageName = $packageName
        silentArgs = $silentArgs
        file = $localFilePath
        logFilePath = $logFilePath
        assumeNewVS2017Installer = $assumeNewVS2017Installer
    }
    Install-VSChocolateyInstallPackage @arguments
}
extensions\Remove-VisualStudioProduct.ps1
function Remove-VisualStudioProduct
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)] [string] $PackageName,
        [Parameter(Mandatory = $true)] [string] $Product,
        [Parameter(Mandatory = $true)] [string] $VisualStudioYear,
        [bool] $Preview
    )
    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' Preview:'$Preview'";
    $channelReference = Get-VSChannelReference -VisualStudioYear $VisualStudioYear -Preview $Preview
    $productReference = Get-VSProductReference -ChannelReference $channelReference -Product $Product
    $packageParameters = @{ channelId = $channelReference.ChannelId; productId = $productReference.ProductId }
    Start-VSModifyOperation `
        -PackageName $PackageName `
        -ArgumentList @() `
        -ChannelReference $channelReference `
        -ApplicableProducts @($Product) `
        -OperationTexts @('uninstalled', 'uninstalling', 'uninstallation') `
        -Operation 'uninstall' `
        -PackageParameters $packageParameters `
        -ProductReference $productReference
    $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,
        [bool] $Preview
    )
    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' Preview:'$Preview'";
    $argumentList = @('remove', "Microsoft.VisualStudio.Workload.$Workload")

    $channelReference = Get-VSChannelReference -VisualStudioYear $VisualStudioYear -Preview $Preview
    Start-VSModifyOperation -PackageName $PackageName -ArgumentList $argumentList -ChannelReference $channelReference -ApplicableProducts $ApplicableProducts -OperationTexts @('uninstalled', 'uninstalling', 'uninstallation')
}
extensions\Remove-VSPackageParametersNotPassedToNativeInstaller.ps1
function Remove-VSPackageParametersNotPassedToNativeInstaller
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [hashtable] $PackageParameters,
        [Parameter(Mandatory = $true)] [string] $TargetDescription,
        [string[]] $Blacklist,
        [string[]] $Whitelist
    )

    Remove-NegatedArguments -Arguments $PackageParameters -RemoveNegativeSwitches

    $hasWhitelist = ($Whitelist | Measure-Object).Count -gt 0
    $parametersToRemove = $PackageParameters.Keys | Where-Object { $Blacklist -contains $_ -or ($hasWhitelist -and $Whitelist -notcontains $_) }
    foreach ($parameterToRemove in $parametersToRemove)
    {
        if ($parameterToRemove -eq $null)
        {
            continue
        }

        Write-Debug "Filtering out package parameter not passed to the ${TargetDescription}: '$parameterToRemove'"
        $PackageParameters.Remove($parameterToRemove)
    }
}
extensions\Resolve-VSProductInstance.ps1
function Resolve-VSProductInstance
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true, ParameterSetName = 'ByProductReference')] [PSObject] $ProductReference,
        [Parameter(Mandatory = $true, ParameterSetName = 'ByChannelReference')] [PSObject] $ChannelReference,
        [Parameter(Mandatory = $true, ParameterSetName = 'AnyProductAndChannel')] [switch] $AnyProductAndChannel,
        [Parameter(Mandatory = $true)] [hashtable] $PackageParameters
    )

    Write-Debug 'Resolving VS product instance(s)'

    $products = Get-WillowInstalledProducts
    if ($ProductReference -ne $null)
    {
        Write-Debug "Detecting instances of VS products with ProductId = '$($ProductReference.ProductId)' ChannelId = '$($ProductReference.ChannelId)'"
        $products = Get-WillowInstalledProducts | Where-Object { $_ -ne $null -and $_.channelId -eq $productReference.ChannelId -and $_.productId -eq $productReference.ProductId }
    }
    elseif ($ChannelReference -ne $null)
    {
        Write-Debug "Detecting instances of VS products with ChannelId = '$($ChannelReference.ChannelId)'"
        $products = Get-WillowInstalledProducts | Where-Object { $_ -ne $null -and $_.channelId -eq $channelReference.ChannelId }
    }
    else
    {
        Write-Debug 'Detecting instances of any VS products'
        $products = Get-WillowInstalledProducts
    }

    if ($PackageParameters.ContainsKey('installPath'))
    {
        $installPath = $PackageParameters['installPath']
        Write-Debug "Filtering detected product instances by installPath: '$installPath'"
        $products = $products | Where-Object { $_ -ne $null -and $_.installationPath -eq $installPath }
    }

    $count = ($products | Measure-Object).Count
    Write-Debug "Resolved $count product instance(s)"
    $products | Write-Output
}
extensions\Uninstall-VisualStudioVsixExtension.ps1
function Uninstall-VisualStudioVsixExtension
{
<#
.SYNOPSIS
Uninstalls a Visual Studio VSIX extension.

.DESCRIPTION
This function uninstalls a Visual Studio VSIX extension by invoking
the Visual Studio extension installer (VSIXInstaller.exe).
The latest installer version found on the machine is used.
The extension is uninstalled from all Visual Studio instances present on the
machine the extension is compatible with.

.PARAMETER PackageName
The name of the package - while this is an arbitrary value, it's
recommended that it matches the package id.
Alias: Name

.PARAMETER VsixId
The Identification of the extension to be uninstalled.
Typically located inside a vsixmanifest file in the software source
repository, or found in the vsix installer after extracting it.
Alias: Id
#>
    [CmdletBinding()]
    Param
    (
        [Alias('Name')] [string] $PackageName,
        [Alias('Id')] [string] $VsixId
    )

    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-VisualStudioVsixExtension' for $PackageName with VsixId:'$VsixId'"

    $packageParameters = Parse-Parameters $env:chocolateyPackageParameters

    $vsixInstaller = Get-VisualStudioVsixInstaller -Latest
    Write-Verbose ('Found VSIXInstaller version {0}: {1}' -f $vsixInstaller.Version, $vsixInstaller.Path)

    $logFileName = 'VSIXInstaller_{0}_{1:yyyyMMddHHmmss}.log' -f $PackageName, (Get-Date)
    $argumentSet = @{
        'uninstall' = $VsixId
        'quiet' = $null
        'admin' = $null
        'logFile' = $logFileName
    }

    Merge-AdditionalArguments -Arguments $argumentSet -AdditionalArguments $packageParameters
    Remove-NegatedArguments -Arguments $argumentSet -RemoveNegativeSwitches
    $exeArgsAsString = ConvertTo-ArgumentString -Arguments $argumentSet -Syntax 'VSIXInstaller'

    Write-Host ('Uninstalling {0} using VSIXInstaller version {1}' -f $PackageName, $vsixInstaller.Version)
    $validExitCodes = @(0, 1002, 2003)
    $exitCode = Start-VSChocolateyProcessAsAdmin -statements $exeArgsAsString -exeToRun $vsixInstaller.Path -validExitCodes $validExitCodes
    if ($exitCode -eq 1002 -or $exitCode -eq 2003) # 1002 is returned by VSIX in VS 2017, and 2003 in earlier versions
    {
        Write-Host "Visual Studio extension '${PackageName}' is already uninstalled."
    }
    else
    {
        Write-Host "Visual Studio extension '${PackageName}' has been uninstalled from all supported Visual Studio instances."
    }
}
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 { $_.NodeType -eq 'Element' -and $_.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)
        {
            Write-Host "Enabling requested feature: $feature"
            $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 | Where-Object { $_.NodeType -eq 'Element' } | 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"
    $notSelectedNodes = $xml.DocumentElement.SelectableItemCustomizations.ChildNodes | Where-Object { $_.NodeType -eq 'Element' -and $_.Selected -eq "no" }
    foreach ($nodeToRemove in $notSelectedNodes)
    {
        Write-Verbose "Removing not selected AdminDeployment node: $($nodeToRemove.Id)"
        $nodeToRemove.ParentNode.RemoveChild($nodeToRemove) | Out-Null
    }
    $xml.Save($adminFile)
}
extensions\Wait-VSInstallerProcesses.ps1
function Wait-VSInstallerProcesses
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)] [ValidateSet('Wait', 'Fail')] $Behavior
    )

    $exitCode = $null

    Write-Debug ('[{0:yyyyMMdd HH:mm:ss.fff}] Looking for still running VS installer processes' -f (Get-Date))
    $lazyQuitterProcessNames = @('vs_installershell', 'vs_installerservice')
    do
    {
        $lazyQuitterProcesses = Get-Process -Name $lazyQuitterProcessNames -ErrorAction SilentlyContinue | Where-Object { $_ -ne $null -and -not $_.HasExited }
        $lazyQuitterProcessCount = ($lazyQuitterProcesses | Measure-Object).Count
        if ($lazyQuitterProcessCount -gt 0)
        {
            try
            {
                Write-Debug "Found $lazyQuitterProcessCount still running Visual Studio installer processes which are known to exit asynchronously:"
                $lazyQuitterProcesses | Sort-Object -Property Name, Id | ForEach-Object { '[{0}] {1}' -f $_.Id, $_.Name } | Write-Debug
                Write-Debug ('[{0:yyyyMMdd HH:mm:ss.fff}] Giving the processes some time to exit' -f (Get-Date))
                $lazyQuitterProcesses | Wait-Process -Timeout 1 -ErrorAction SilentlyContinue
                Write-Debug ('[{0:yyyyMMdd HH:mm:ss.fff}] Looking for still running VS installer processes' -f (Get-Date))
            }
            finally
            {
                $lazyQuitterProcesses | ForEach-Object { $_.Dispose() }
                $lazyQuitterProcesses = $null
            }
        }
    }
    while ($lazyQuitterProcessCount -gt 0)

    # This sometimes happens when the VS installer is updated by the invoked bootstrapper.
    # The initial process exits, leaving another instance of the VS installer performing the actual install in the background.
    # This happens despite passing '--wait'.
    $vsInstallerProcessNames = @('vs_bootstrapper', 'vs_setup_bootstrapper', 'vs_installer', 'vs_installershell', 'vs_installerservice')
    do
    {
        $vsInstallerProcesses = Get-Process -Name $vsInstallerProcessNames -ErrorAction SilentlyContinue | Where-Object { $_ -ne $null -and -not $_.HasExited }
        $vsInstallerProcessCount = ($vsInstallerProcesses | Measure-Object).Count
        if ($vsInstallerProcessCount -gt 0)
        {
            try
            {
                Write-Warning "Found $vsInstallerProcessCount still running Visual Studio installer processes:"
                $vsInstallerProcesses | Sort-Object -Property Name, Id | ForEach-Object { '[{0}] {1}' -f $_.Id, $_.Name } | Write-Warning

                if ($Behavior -eq 'Fail')
                {
                    throw 'There are Visual Studio installer processes already running. Installation cannot continue.'
                }

                foreach ($p in $vsInstallerProcesses)
                {
                    [void] $p.Handle # make sure we get the exit code http://stackoverflow.com/a/23797762/266876
                }
                Write-Warning "Waiting for the processes to finish..."
                Write-Debug ('[{0:yyyyMMdd HH:mm:ss.fff}] Waiting for the processes to finish' -f (Get-Date))
                $vsInstallerProcesses | Wait-Process -Timeout 60 -ErrorAction SilentlyContinue
                foreach ($proc in $vsInstallerProcesses)
                {
                    if (-not $proc.HasExited)
                    {
                        continue
                    }
                    if ($exitCode -eq $null)
                    {
                        $exitCode = $proc.ExitCode
                    }
                    Write-Debug ("[{0:yyyyMMdd HH:mm:ss.fff}] $($proc.Name) process $($proc.Id) exited with code '$($proc.ExitCode)'" -f (Get-Date))
                    if ($proc.ExitCode -ne 0 -and $proc.ExitCode -ne $null)
                    {
                        Write-Warning "$($proc.Name) process $($proc.Id) exited with code $($proc.ExitCode)"
                        if ($exitCode -eq 0)
                        {
                            $exitCode = $proc.ExitCode
                        }
                    }
                }

                Write-Debug ('[{0:yyyyMMdd HH:mm:ss.fff}] Looking for still running VS installer processes' -f (Get-Date))
            }
            finally
            {
                $vsInstallerProcesses | ForEach-Object { $_.Dispose() }
                $vsInstallerProcesses = $null
            }
        }
        else
        {
            Write-Debug 'Did not find any running VS installer processes.'
        }
    }
    while ($vsInstallerProcessCount -gt 0)

    # 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 ('[{0:yyyyMMdd HH:mm:ss.fff}] Looking for vs_installer.windows.exe processes spawned by the uninstaller' -f (Get-Date))
    do
    {
        $uninstallerProcesses = Get-Process -Name 'vs_installer.windows' -ErrorAction SilentlyContinue | Where-Object { $_ -ne $null -and -not $_.HasExited }
        $uninstallerProcessesCount = ($uninstallerProcesses | Measure-Object).Count
        if ($uninstallerProcessesCount -gt 0)
        {
            try
            {
                if ($Behavior -eq 'Fail')
                {
                    Write-Warning "Found $uninstallerProcessesCount vs_installer.windows.exe process(es): $($uninstallerProcesses | Select-Object -ExpandProperty Id)"
                    throw 'There are Visual Studio installer processes already running. Installation cannot continue.'
                }

                Write-Debug "Found $uninstallerProcessesCount vs_installer.windows.exe process(es): $($uninstallerProcesses | Select-Object -ExpandProperty Id)"
                Write-Debug ('[{0:yyyyMMdd HH:mm:ss.fff}] Waiting for all vs_installer.windows.exe processes to become input-idle' -f (Get-Date))
                foreach ($p in $uninstallerProcesses)
                {
                    [void] $p.Handle # make sure we get the exit code http://stackoverflow.com/a/23797762/266876
                    $waitSeconds = 60
                    try
                    {
                        $result = $p.WaitForInputIdle($waitSeconds * 1000)
                    }
                    catch [InvalidOperationException]
                    {
                        $result = $false
                    }

                    if ($result)
                    {
                        Write-Debug "Process $($p.Id) has reached input idle state"
                    }
                    else
                    {
                        Write-Debug "Process $($p.Id) has not reached input idle state after $waitSeconds seconds, continuing regardless"
                    }
                }
                Write-Debug ('[{0:yyyyMMdd HH:mm:ss.fff}] Sending CloseMainWindow to all vs_installer.windows.exe processes' -f (Get-Date))
                foreach ($p in $uninstallerProcesses)
                {
                    $result = $p.CloseMainWindow()
                    if ($result)
                    {
                        Write-Debug "Successfully sent CloseMainWindow to process $($p.Id)"
                    }
                    else
                    {
                        Write-Debug "Failed to send CloseMainWindow to process $($p.Id), continuing regardless"
                    }
                }
                Write-Debug ('[{0:yyyyMMdd HH:mm:ss.fff}] Waiting for all vs_installer.windows.exe processes to exit' -f (Get-Date))
                $uninstallerProcesses | Wait-Process -Timeout 60 -ErrorAction SilentlyContinue
                foreach ($proc in $uninstallerProcesses)
                {
                    if (-not $proc.HasExited)
                    {
                        continue
                    }
                    if ($exitCode -eq $null)
                    {
                        $exitCode = $proc.ExitCode
                    }
                    Write-Debug ("[{0:yyyyMMdd HH:mm:ss.fff}] $($proc.Name) process $($proc.Id) exited with code '$($proc.ExitCode)'" -f (Get-Date))
                    if ($proc.ExitCode -ne 0 -and $proc.ExitCode -ne $null)
                    {
                        Write-Warning "$($proc.Name) process $($proc.Id) exited with code $($proc.ExitCode)"
                        if ($exitCode -eq 0)
                        {
                            $exitCode = $proc.ExitCode
                        }
                    }
                }

                Write-Debug ('[{0:yyyyMMdd HH:mm:ss.fff}] Looking for vs_installer.windows.exe processes spawned by the uninstaller' -f (Get-Date))
            }
            finally
            {
                $uninstallerProcesses | ForEach-Object { $_.Dispose() }
                $uninstallerProcesses = $null
            }
        }
        else
        {
            Write-Debug 'Did not find any running vs_installer.windows.exe processes.'
        }
    }
    while ($uninstallerProcessesCount -gt 0)

    return $exitCode
}
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.

### Get-VisualStudioVsixInstaller

Locates all versions of the Visual Studio extension installer installed on the machine.
The returned object contain properties: Path, Version.
Supports Visual Studio 2017 and earlier Visual Studio versions.

### Install-VisualStudioVsixExtension

Installs or updates a Visual Studio extension (*.vsix).
Replaces Install-ChocolateyVsixPackage, adding support for Visual Studio 2017.

## 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'

    Install-VisualStudioVsixExtension `
        -PackageName 'stylecop-vsix'
        -VsixUrl 'https://chrisdahlberg.gallerycdn.vsassets.io/extensions/chrisdahlberg/stylecop/5.0.6419.0/1501345807969/231103/4/StyleCop.vsix'
        -Checksum '212738A32AB1AF0EDE8C42F1B574EE6A67A88E69AF7EFD744E48B9AD05EE84A5'
        -ChecksumType 'sha256'

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.
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'

    $packageParameters = Parse-Parameters $env:chocolateyPackageParameters
    if ($assumeNewVS2017Installer)
    {
        $vsInstaller = Get-VisualStudioInstaller
        if ($vsInstaller -eq $null)
        {
            Write-Warning "Uninstall information for $PackageName could not be found. This probably means the application was uninstalled outside Chocolatey."
            return
        }

        $uninstallerPath = $vsInstaller.Path
        $logFilePath = $null
    }
    else
    {
        $uninstallerPath = Get-VSUninstallerExePath `
            -PackageName $PackageName `
            -UninstallerName $UninstallerName `
            -ProgramsAndFeaturesDisplayName $ProgramsAndFeaturesDisplayName `
            -AssumeNewVS2017Installer:$assumeNewVS2017Installer

        $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
}

Log in or click on link to see number of positives.

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.

Add to Builder Version Downloads Last Updated Status
Chocolatey Visual Studio servicing extensions 1.11.0 1253182 Saturday, June 3, 2023 Approved
Chocolatey Visual Studio servicing extensions 1.11.0-preview7 150 Friday, May 5, 2023 Exempted
Chocolatey Visual Studio servicing extensions 1.10.2 4113374 Sunday, May 15, 2022 Exempted
Chocolatey Visual Studio servicing extensions 1.10.1 33841 Thursday, May 12, 2022 Exempted
Chocolatey Visual Studio servicing extensions 1.10.0 2644429 Wednesday, October 6, 2021 Exempted
Chocolatey Visual Studio servicing extensions 1.10.0-preview5 164 Saturday, October 2, 2021 Exempted
Chocolatey Visual Studio servicing extensions 1.10.0-preview4 192 Sunday, September 26, 2021 Exempted
Chocolatey Visual Studio servicing extensions 1.10.0-preview3 174 Monday, September 20, 2021 Exempted
Chocolatey Visual Studio servicing extensions 1.10.0-preview2 461 Friday, June 25, 2021 Exempted
Chocolatey Visual Studio servicing extensions 1.10.0-preview1 605 Saturday, March 6, 2021 Approved
Chocolatey Visual Studio servicing extensions 1.9.0 2343356 Sunday, February 21, 2021 Approved
Chocolatey Visual Studio servicing extensions 1.8.1 4093340 Sunday, June 9, 2019 Approved
Chocolatey Visual Studio servicing extensions 1.8.0 217940 Saturday, March 9, 2019 Approved
Chocolatey Visual Studio servicing extensions 1.8.0-preview4 386 Friday, January 18, 2019 Approved
Chocolatey Visual Studio servicing extensions 1.7.1 196234 Tuesday, November 27, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.7.0 209262 Monday, May 28, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.7.0-rc4 484 Sunday, May 20, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.7.0-rc3 363 Saturday, May 19, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.7.0-rc2 385 Wednesday, May 16, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.6.0 17126 Saturday, March 10, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.6.0-rc9 376 Wednesday, March 7, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.6.0-rc8 395 Saturday, March 3, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.6.0-rc7 433 Thursday, March 1, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.6.0-rc6 376 Sunday, February 11, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.6.0-rc1 415 Sunday, February 11, 2018 Approved
Chocolatey Visual Studio servicing extensions 1.5.1 17373 Saturday, December 9, 2017 Approved
Chocolatey Visual Studio servicing extensions 1.5.0 10944 Friday, October 6, 2017 Approved
Chocolatey Visual Studio servicing extensions 1.4.1 8552 Monday, June 19, 2017 Approved
Chocolatey Visual Studio servicing extensions 1.4.0 2435 Monday, June 5, 2017 Approved
Chocolatey Visual Studio servicing extensions 1.3.0 1439 Friday, May 19, 2017 Approved
Chocolatey Visual Studio servicing extensions 1.2.0 4061 Saturday, March 4, 2017 Approved
Chocolatey Visual Studio servicing extensions 1.1.0 554 Wednesday, March 1, 2017 Approved
Chocolatey Visual Studio servicing extensions 1.0.0 596 Friday, February 17, 2017 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