Downloads:
20,425,886
Downloads of v 1.11.1:
5,249,392
Last Update:
16 Sep 2023
Package Maintainer(s):
Software Author(s):
- Jakub Bereżański
Tags:
chocolatey extension admin visual studio- Software Specific:
- Software Site
- Software License
- Software Docs
- Software Issues
- Package Specific:
- Package Source
- Package outdated?
- Package broken?
- Contact Maintainers
- Contact Site Admins
- Software Vendor?
- Report Abuse
- Download
Chocolatey Visual Studio servicing extensions
- 1
- 2
- 3
1.11.1 | Updated: 16 Sep 2023
- Software Specific:
- Software Site
- Software License
- Software Docs
- Software Issues
- Package Specific:
- Package Source
- Package outdated?
- Package broken?
- Contact Maintainers
- Contact Site Admins
- Software Vendor?
- Report Abuse
- Download
Downloads:
20,425,886
Downloads of v 1.11.1:
5,249,392
Maintainer(s):
Software Author(s):
- Jakub Bereżański
Chocolatey Visual Studio servicing extensions 1.11.1
Legal Disclaimer: Neither this package nor Chocolatey Software, Inc. are affiliated with or endorsed by Jakub Bereżański. The inclusion of Jakub Bereżański trademark(s), if any, upon this webpage is solely to identify Jakub Bereżański goods or services and not for commercial purposes.
- 1
- 2
- 3
Some Checks Have Failed or Are Not Yet Complete
Not All Tests Have Passed
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:
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
Option 1: Cached Package (Unreliable, Requires Internet - Same As Community)-
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
-
Open Source
-
Download the package:
Download - Follow manual internalization instructions
-
-
Package Internalizer (C4B)
-
Run: (additional options)
choco download chocolatey-visualstudio.extension --internalize --source=https://community.chocolatey.org/api/v2/
-
For package and dependencies run:
choco push --source="'INTERNAL REPO URL'"
- Automate package internalization
-
Run: (additional options)
3. Copy Your Script
choco upgrade chocolatey-visualstudio.extension -y --source="'INTERNAL REPO URL'" [other options]
See options you can pass to upgrade.
See best practices for scripting.
Add this to a PowerShell script or use a Batch script with tools and in places where you are calling directly to Chocolatey. If you are integrating, keep in mind enhanced exit codes.
If you do use a PowerShell script, use the following to ensure bad exit codes are shown as failures:
choco upgrade chocolatey-visualstudio.extension -y --source="'INTERNAL REPO URL'"
$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.11.1'
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.11.1'
end
See docs at https://docs.chef.io/resource_chocolatey_package.html.
cChocoPackageInstaller chocolatey-visualstudio.extension
{
Name = "chocolatey-visualstudio.extension"
Version = "1.11.1"
Source = "INTERNAL REPO URL"
}
Requires cChoco DSC Resource. See docs at https://github.com/chocolatey/cChoco.
package { 'chocolatey-visualstudio.extension':
ensure => '1.11.1',
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.
This package is exempt from moderation. While it is likely safe for you, there is more risk involved.
This package provides helper functions useful for developing packages for installing and servicing Microsoft Visual Studio.
For best results, it is recommended to install the VSSetup PowerShell module before installing any Visual Studio packages.
# CHANGELOG
## Version 1.11.1
- Fixed layout creation (`--layout`) broken by adding `--channelId` and `--channelUri` in support of the generic bootstrapper ([GH-148](https://github.com/jberezanski/ChocolateyPackages/issues/148)).
## Version 1.11.0
- Arguments `--path install=...`, `--path cache=...` and `--path shared=...` are now supported ([GH-142](https://github.com/jberezanski/ChocolateyPackages/issues/142)). `--path install=...` is converted to `--installPath`; those two must not be specified at the same time with different values.
- Packages may now specify default values for some package parameters and pass them to Install-VisualStudio, Add-VisualStudioWorkload/Component and Remove-VisualStudioWorkload/Component (via a new -DefaultParameterValues parameter). This, in particular, supports packages which embed the VS bootstrapper and manifests in order to install a specific VS version, or packages which want to install/update VS from the LTSC channel ([GH-139](https://github.com/jberezanski/ChocolateyPackages/pull/139)).
- The parameters parser now understands the syntax `--reset-parameter-xyz` as a directive to forget the parameter `--xyz` if it has already been specified (possibly via default values set by the package). This is intended to be a way to override some defaults set in the package wihout having to provide an explicit value (i.e. allow the normal VS Installer and/or extension script logic to determine the value).
- Install-VisualStudio now respects `--channelId` from package parameters for the purpose of determining an existing VS instance to update ([GH-139](https://github.com/jberezanski/ChocolateyPackages/pull/139)).
- Package parameters can now be specified multiple times and the last value will be used.
- VS Installer parameters which cannot be used when updating an already installed instance will be ignored when passed as package parameters. This avoids failures when package parameters remembered from the initial installation are reused by Chocolatey for upgrades when the 'useRememberedArgumentsForUpgrades' feature is enabled ([GH-99](https://github.com/jberezanski/ChocolateyPackages/issues/99)).
- Fixed reading of installer version from the channel manifest for VS 2022, which caused a harmless warning and triggered unnecessary attempts to upgrade the VS Installer.
- Install-VisualStudio now automatically sets `--channelId`, `--channelUri` and `--productId` when installing a new VS instance. (This supports using the generic bootstrapper, vs_Setup.exe, to install any product available from the given channel.)
## Version 1.10.2
- When installation fails, Visual Studio Installer logs are now examined and content of any error logs is printed as warnings, which should help in troubleshooting installation issues (including the unhelpful -1 exit code).
## Version 1.10.1
- Fixed clearing the VS Installer channel cache on recent VS Installer versions ([GH-127](https://github.com/jberezanski/ChocolateyPackages/issues/127)).
## Version 1.10.0
- When checking if the Visual Studio Installer needs update, channels of other installed Visual Studio products are also used to determine the highest required installer version. This aligns with the native Visual Studio Installer behavior and prevents the Installer from exiting early to perform a self-update when, for example, installing or upgrading Visual Studio 2017 on a machine with Visual Studio 2019 installed ([GH-97](https://github.com/jberezanski/ChocolateyPackages/issues/97)).
- Fixed uninstallation of modern versions of the Visual Studio Installer.
- During an update operation, if the package author did not provide DesiredProductVersion, the version is automatically determined from the channel manifest. This lights up two features:
- The update process is short-circuited if the installed product version is already DesiredProductVersion or higher.
- After the update, the installed product version is checked to determine if the update actually happened. This makes it possible to detect a bug in the Visual Studio installer, which sometimes fails to download the channel manifest and thinks no update is needed.
- Fixed installed products detection being invoked twice by mistake.
- Updated workaround for the bootstrapper ignoring --wait when updating the VS Installer to account for a new process used by the VS Installer in 16.9+ ([GH-7](https://github.com/jberezanski/ChocolateyPackages/issues/7), [GH-97](https://github.com/jberezanski/ChocolateyPackages/issues/97)).
- Install-VisualStudio, Add-VisualStudioWorkload/Component and Remove-VisualStudioProduct/Workload/Component now support Visual Studio 2022 (-VisualStudioYear 2022).
## Version 1.9.0
- Added custom handling for '--installCatalogUri' to better support installations from layout without '--noWeb' ([GH-65](https://github.com/jberezanski/ChocolateyPackages/pull/65)).
- New switch for Add-VisualStudioWorkload: -IncludeOptionalComponentsByDefault ([GH-92](https://github.com/jberezanski/ChocolateyPackages/pull/92)).
- Fixed support for Visual Studio 2019 16.9 installer, which is no longer based on Electron.
## Version 1.8.1
- The VSSetup PowerShell module, if present, is used to detect VS instances [(GH-9](https://github.com/jberezanski/ChocolateyPackages/issues/9)). This protects against future failures due to changes in the (undocumented) VS instance info storage format. On PowerShell 5+ (also 3 and 4 with the PackageManagement Preview module installed) this module can be installed using `Install-Module -Name VSSetup`.
- (On systems without VSSetup) Fixed detection of installed VS instances when package cache had been moved from the default location [(GH-49](https://github.com/jberezanski/ChocolateyPackages/issues/49), thanks @bryan5989!).
- Fixed clean install of VS 2019 16.1+ (which fails to install the VS installer via --quiet --update if it is not installed or is same version). Install-VisualStudioInstaller remains broken. [(GH-64](https://github.com/jberezanski/ChocolateyPackages/issues/64))
## 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 ([electron#12695](https://github.com/electron/electron/issues/12695), [electron#24360](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.
# 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"
##### Install the latest version of VS 2022 Professional from the Internet or update an already installed instance, specifying a custom nickname and installation path. Use the English language for the installation process and as the default VS language.
cinst visualstudio2022professional --params "--locale en-US --installPath C:\VS 2022 Pro --nickname Pro"
##### Install the latest version of VS 2022 Professional from the Internet (do not attempt to update if already installed), specifying all possible custom paths. Use the English language for the installation process and as the default VS language. Install all recommanded and optional workloads.
cinst visualstudio2022buildtools --params "--locale en-US --path install=C:\VS 2022 BT --path shared=C:\VS 2022 Shared --path cache=C:\VS 2022 Cache --no-update --includeRecommended --includeOptional"
## 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"
# 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.
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,
[hashtable] $DefaultParameterValues
)
if ($null -ne $Env:ChocolateyPackageDebug)
{
$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")
$packageParameters = Parse-Parameters $env:chocolateyPackageParameters -DefaultValues $DefaultParameterValues
$channelReference = Get-VSChannelReference -VisualStudioYear $VisualStudioYear -Preview:$Preview -PackageParameters $packageParameters
Start-VSModifyOperation `
-PackageName $PackageName `
-PackageParameters $packageParameters `
-ArgumentList $argumentList `
-ChannelReference $channelReference `
-ApplicableProducts $ApplicableProducts `
-RequiredProductVersion $RequiredProductVersion `
-OperationTexts @('installed', 'installing', 'installation')
}
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,
[switch] $IncludeOptionalComponentsByDefault,
[version] $RequiredProductVersion,
[bool] $Preview,
[hashtable] $DefaultParameterValues
)
if ($null -ne $Env:ChocolateyPackageDebug)
{
$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', '')
}
if ($IncludeOptionalComponentsByDefault)
{
$argumentList += @('includeOptional', '')
}
$packageParameters = Parse-Parameters $env:chocolateyPackageParameters -DefaultValues $DefaultParameterValues
$channelReference = Get-VSChannelReference -VisualStudioYear $VisualStudioYear -Preview:$Preview -PackageParameters $packageParameters
Start-VSModifyOperation `
-PackageName $PackageName `
-PackageParameters $packageParameters `
-ArgumentList $argumentList `
-ChannelReference $channelReference `
-ApplicableProducts $ApplicableProducts `
-RequiredProductVersion $RequiredProductVersion `
-OperationTexts @('installed', 'installing', 'installation')
}
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
}
Write-Verbose 'Checking installer version required by the package'
$packageRequiredVersionInfo = Get-VSRequiredInstallerVersion -PackageParameters $PackageParameters -ChannelReference $ChannelReference -UseInstallChannelUri:$UseInstallChannelUri `
| Add-Member -PassThru -NotePropertyMembers @{ ForPackage = $true; Source = 'package' }
# If there are other VS products installed (e.g. we are installing/updating VS 2017 and a 2019 product is installed),
# the VS Installer will also check other channels for installer update requirement.
$installedProductsUpdateableChannels = Get-WillowInstalledProducts `
| Where-Object { $null -ne $_ } `
| ForEach-Object { New-VSChannelReference -ChannelId $_.channelId -ChannelUri $_.channelUri } `
| Where-Object { -not [string]::IsNullOrEmpty($_.ChannelUri) <# may be empty to disable updates #> } `
| Sort-Object -Property ChannelId, ChannelUri -Unique
$otherChannelsToCheck = $installedProductsUpdateableChannels | Where-Object { $null -eq $ChannelReference -or $ChannelReference.ChannelId -ne $_.ChannelId }
$otherRequiredVersionInfos = @()
if (($otherChannelsToCheck | Measure-Object).Count -gt 0)
{
if (-not $PackageParameters.ContainsKey('noWeb'))
{
Write-Verbose 'Checking installer version required by installed Visual Studio product(s) from other channel(s)'
$otherRequiredVersionInfos = @($otherChannelsToCheck `
| ForEach-Object {
Get-VSRequiredInstallerVersion -ChannelReference $_ -PackageParameters @{} `
| Add-Member -PassThru -NotePropertyMembers @{ ForPackage = $false; Source = "channel $($_.ChannelId)"; ChannelReference = $_ }
})
}
else
{
Write-Verbose 'Not checking installer version required by installed Visual Studio product(s) from other channel(s) because --noWeb was passed in package parameters.'
}
}
$allRequiredVersionInfos = @($packageRequiredVersionInfo) + $otherRequiredVersionInfos
$requiredVersionInfo = $allRequiredVersionInfos | Sort-Object -Property Version,EngineVersion -Descending | Select-Object -First 1
Write-Verbose "Highest required installer version: $($requiredVersionInfo.Version) (engine: $($requiredVersionInfo.EngineVersion)); requirement source: $($requiredVersionInfo.Source)"
if ($requiredVersionInfo.ForPackage)
{
# Installing the VS Installer update from the channel of this package,
# so supporting all normal features (offline layout, explicit bootstrapper path etc).
Install-VSInstaller `
-DoNotInstallIfNotPresent `
-RequiredInstallerVersion $requiredVersionInfo.Version `
-RequiredEngineVersion $requiredVersionInfo.EngineVersion `
@PSBoundParameters
}
else
{
# Installing the VS Installer update from a different channel than this package,
# so using the default manifest source for the other channel
# and the default bootstrapper location from the channel manifest.
Install-VSInstaller `
-DoNotInstallIfNotPresent `
-RequiredInstallerVersion $requiredVersionInfo.Version `
-RequiredEngineVersion $requiredVersionInfo.EngineVersion `
-ChannelReference $requiredVersionInfo.ChannelReference `
-PackageName $PackageName `
-PackageParameters @{}
}
}
Set-StrictMode -Version 2
$ErrorActionPreference = 'Stop'
$scriptRoot = Split-Path -Path $MyInvocation.MyCommand.Definition
Get-ChildItem -Path "$scriptRoot\*.ps1" | ForEach-Object { . $_ }
Export-ModuleMember -Function '*-VisualStudio*'
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 -Force | Remove-Item -Recurse -Force -ErrorAction Continue
}
}
function Close-VSInstallSource
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)] [PSObject] $InstallSourceInfo
)
if ($null -ne $InstallSourceInfo.MountedDiskImage)
{
Write-Host "Dismounting ISO"
$InstallSourceInfo.MountedDiskImage | Dismount-DiskImage
}
else
{
Write-Verbose "No ISO to dismount"
}
}
function Convert-VSProductReferenceToChannelReference
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)] [AllowNull()] [PSObject] $ProductReference
)
if ($null -eq $ProductReference)
{
return $null
}
$cr = New-VSChannelReference `
-ChannelId $ProductReference.ChannelId `
-ChannelUri $ProductReference.ChannelUri `
-InstallChannelUri $ProductReference.InstallChannelUri
return $cr
}
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 ($null -eq $kvp.Value -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
}
# 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 ($null -ne ($adminFile -as [System.URI]).AbsoluteURI)
{
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
}
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
}
function Generate-UninstallArgumentsString
{
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[hashtable] $parameters,
[string] $logFilePath,
[switch] $assumeNewVS2017Installer,
[bool] $supportsNoRestart
)
Write-Debug "Running 'Generate-UninstallArgumentsString' with logFilePath:'$logFilePath', assumeNewVS2017Installer:'$assumeNewVS2017Installer', supportsNoRestart:'$supportsNoRestart'";
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()
if ($supportsNoRestart)
{
$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
}
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)
Traits (System.String[])
#>
[CmdletBinding()]
Param
(
)
$rxVersion = [regex]'"version":\s+"(?<value>[0-9\.]+)"'
$basePaths = @(${Env:ProgramFiles}, ${Env:ProgramFiles(x86)}, ${Env:ProgramW6432})
$installer = $basePaths | Where-Object { $null -ne $_ } | 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'
$setupExePath = Join-Path -Path $candidateDirPath -ChildPath 'setup.exe'
if (Test-Path -Path $versionJsonPath)
{
# old, Electron-based app
$source = 'package.json'
$text = Get-Content -Path $versionJsonPath
$matchesCollection = $rxVersion.Matches($text)
foreach ($match in $matchesCollection)
{
if ($null -eq $match -or -not $match.Success)
{
continue
}
$value = $match.Groups['value'].Value
try
{
$version = [version]$value
Write-Debug ('Parsed Visual Studio Installer version from {0}: {1}' -f $source, $version)
break
}
catch
{
Write-Warning ('Unable to parse Visual Studio Installer version ''{0}'' from {1}' -f $value, $source)
}
}
}
elseif (Test-Path -Path $setupExePath)
{
$source = 'setup.exe'
$setupExeItem = Get-Item -Path $setupExePath
$value = $setupExeItem.VersionInfo.FileVersion
try
{
$version = [version]$value
Write-Debug ('Parsed Visual Studio Installer version from {0}: {1}' -f $source, $version)
}
catch
{
Write-Warning ('Unable to parse Visual Studio Installer version ''{0}'' from {1}' -f $value, $source)
}
}
else
{
Write-Warning ('Visual Studio Installer version information not found in {0}' -f $candidateDirPath)
}
$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)
}
$traits = @()
if ($version -lt [version]'2.9')
{
# Before Visual Studio 2019 16.9 (VS Installer 2.9.*), the installer supported the --norestart switch for the special /uninstall command.
$traits += 'SelfUninstallNoRestart'
}
$installerExePath = Join-Path -Path $candidateDirPath -ChildPath 'vs_installer.exe'
$props = @{
Path = $installerExePath
Version = $version
EngineVersion = $engineVersion
Traits = ([string[]]$traits)
}
$obj = New-Object -TypeName PSObject -Property $props
Write-Verbose ('Visual Studio Installer version {0} (engine version {1}) (traits: {3}) is present ({2}).' -f $obj.Version, $obj.EngineVersion, $obj.Path, ($obj.Traits -join ' '))
$health = $obj | Get-VisualStudioInstallerHealth -Version $version
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
}
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,
[version] $Version
)
Process
{
if ($Path -like '*.exe')
{
$dirPath = Split-Path -Path $Path
}
else
{
$dirPath = $Path
}
if ($null -eq $Version)
{
# be conservative
$expectedFiles = @('vs_installer.exe')
}
elseif ($Version -lt [version]'2.9')
{
$expectedFiles = @('vs_installer.exe', 'vs_installershell.exe', 'node.dll', 'ffmpeg.dll')
}
else
{
$expectedFiles = @('vs_installer.exe', 'vs_installershell.exe', 'setup.exe')
}
$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
}
}
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 { $null -ne $_ } | 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 { $null -ne $_ } | ForEach-Object {
$props = @{
InstallationPath = $_.Path
InstallationVersion = $_.Version
ProductId = $null
ChannelId = $null
}
$obj = New-Object -TypeName PSObject -Property $props
Write-Output $obj
}
}
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 { $null -ne $_ } `
| 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 { $null -ne $_ } `
| 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
}
}
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
}
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 ($null -ne $ChannelReference)
{
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 ($null -eq $manifestUri)
{
# 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 ($null -ne $ChannelReference)
{
$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 ($null -ne $channelId)
{
$manifestUri = Get-VSChannelUri -ChannelId $channelId -ErrorAction SilentlyContinue
}
}
if ($null -eq $manifestUri)
{
# 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
}
function Get-VSChannelManifestItem
{
[OutputType([Collections.IDictionary])]
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)] [System.Collections.IDictionary] $Manifest,
[ValidateSet('Bootstrapper', 'Manifest', 'ChannelProduct')] [Parameter(Mandatory = $true)] [string] $ChannelItemType,
[string] $Id
)
if ($Id -eq '')
{
$searchDesc = "type $ChannelItemType"
$additionalFilter = { $true }
$expectSingle = $ChannelItemType -ne 'ChannelProduct'
}
else
{
$searchDesc = "type $ChannelItemType and id $Id"
$additionalFilter = { $_.ContainsKey('id') -and $_['id'] -eq $Id }
$expectSingle = $true
}
$totalCount = 0
if ($Manifest -is [Collections.IDictionary] -and $Manifest.ContainsKey('channelItems'))
{
$channelItems = $Manifest['channelItems']
if ($channelItems -is [array])
{
$matchingItems = @($channelItems | Where-Object { $_ -is [Collections.IDictionary] -and $_.ContainsKey('type') -and $_['type'] -eq $ChannelItemType } | Where-Object $additionalFilter)
$matchingItemsCount = ($matchingItems | Measure-Object).Count
if ($matchingItemsCount -eq 0)
{
Write-Debug "Manifest parsing error: zero channelItem objects found of $searchDesc"
}
elseif ($expectSingle -and $matchingItemsCount -gt 1)
{
Write-Debug "Manifest parsing error: expected 1 but found $matchingItemsCount channelItem objects of $searchDesc"
}
else
{
foreach ($channelItem in $matchingItems)
{
if ($channelItem -is [Collections.IDictionary])
{
Write-Output $channelItem
$totalCount += 1
}
else
{
Write-Debug 'Manifest parsing error: channelItem is not IDictionary'
}
}
}
}
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 ($totalCount -ne 0)
{
Write-Debug "Located $totalCount channel manifest item(s) of $searchDesc"
}
else
{
Write-Debug "Could not locate any channel manifest item(s) of $searchDesc"
}
}
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
}
}
function Get-VSChannelManifestItemVersion
{
[OutputType([System.Version])]
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)] [System.Collections.IDictionary] $Manifest,
[ValidateSet('Bootstrapper', 'Manifest', 'ChannelProduct')] [Parameter(Mandatory = $true)] [string] $ChannelItemType,
[string] $Id,
[string] $PropertyName = 'version'
)
$versionObject = $null
$channelItem = Get-VSChannelManifestItem -Manifest $Manifest -ChannelItemType $ChannelItemType -Id $Id
if (($channelItem | Measure-Object).Count -eq 1 -and $channelItem -is [Collections.IDictionary] -and $channelItem.ContainsKey($PropertyName))
{
$versionString = $channelItem[$PropertyName]
if ($versionString -is [string])
{
if (-not [version]::TryParse($versionString, [ref]$versionObject))
{
Write-Debug "Manifest parsing error: property '$PropertyName' value '$versionString' failed to parse as System.Version"
}
}
else
{
Write-Debug "Manifest parsing error: property '$PropertyName' value is not a string"
}
}
else
{
Write-Debug "Manifest parsing error: channelItem is not IDictionary or does not contain property '$PropertyName'"
}
if ($null -ne $versionObject)
{
Write-Verbose "$ChannelItemType $Id $PropertyName determined from the channel manifest: $versionObject"
return $versionObject
}
else
{
Write-Verbose "The $ChannelItemType $Id $PropertyName could not be determined from the channel manifest"
return $null
}
}
function Get-VSChannelReference
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)] [ValidateSet('2017', '2019', '2022')] [string] $VisualStudioYear,
[bool] $Preview,
[hashtable] $PackageParameters
)
$channelId = $null
$channelUri = $null
$installChannelUri = $null
if ($null -ne $PackageParameters)
{
if ($PackageParameters.ContainsKey('channelId'))
{
$channelId = $PackageParameters['channelId']
}
if ($PackageParameters.ContainsKey('channelUri'))
{
$channelUri = $PackageParameters['channelUri']
}
if ($PackageParameters.ContainsKey('installChannelUri'))
{
$installChannelUri = $PackageParameters['installChannelUri']
}
}
if ($null -eq $channelId)
{
switch ($VisualStudioYear)
{
'2017' { $majorVersion = 15 }
'2019' { $majorVersion = 16 }
'2022' { $majorVersion = 17 }
default { throw "Unsupported VisualStudioYear: $VisualStudioYear"}
}
$mapPreviewOrReleaseToChannelTypeSuffix = @{ $true = 'Preview'; $false = 'Release' }
$channelId = 'VisualStudio.{0}.{1}' -f $majorVersion, $mapPreviewOrReleaseToChannelTypeSuffix[$Preview]
}
if ($null -eq $channelUri)
{
$channelUri = Get-VSChannelUri -ChannelId $channelId -ErrorAction SilentlyContinue
}
$obj = New-VSChannelReference -ChannelId $channelId -ChannelUri $channelUri -InstallChannelUri $installChannelUri
return $obj
}
function Get-VSChannelUri
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)] [string] $ChannelId
)
$manifestUri = $null
$success = $ChannelId -match '^VisualStudio\.(?<version>\d+)\.(?<kind>[\w\.0-9]+)$' # VisualStudio.15.Release, VisualStudio.17.Release.LTSC.17.4
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
{
$msg = "Channel id '$ChannelId' does not match the expected pattern and cannot be used to compute the channel manifest URI"
Write-Debug $msg
Write-Error $msg
}
return $manifestUri
}
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
}
# https://docs.microsoft.com/en-us/visualstudio/install/use-command-line-parameters-to-install-visual-studio?view=vs-2017#layout-options
if ($packageParameters.ContainsKey('installCatalogUri'))
{
<#
Advanced install options: Parameter --installCatalogUri <uri>
Optional: The URI of the catalog manifest to use for the installation. If specified, the channel manager attempts to download
the catalog manifest from this URI before using the URI in the install channel manifest. This parameter is used to support offline
install, where the layout cache will be created with the product catalog already downloaded. This can be used for the install command;
it is ignored for other commands.
#>
Write-Debug 'Obtaining the installCatalogUri from the Parameters'
$installCatalogUri = $packageParameters['installCatalogUri']
if ([string]::IsNullOrEmpty($installCatalogUri))
{
Write-Verbose 'The installCatalogUri parameter was present in package parameters, but empty. The component manifest will be loaded from the url supplied in the channel manifest (default behavior).'
# If the installCatalogUri is null continue with the url from the ChannelManifest as the Microsoft documentation says.
}
else
{
try
{
Write-Verbose 'Attempting to obtain the component manifest from installCatalogUri provided via package parameters'
return Get-VSManifest -Description 'catalog manifest' -Url $installCatalogUri -LayoutFileName 'Catalog.json' -LayoutPath $layoutPath
}
catch
{
# The catalog manifest could not be downloaded from the installCatalogUri.
# Catch the error and continue with the url from the ChannelManifest as the Microsoft documentation says.
$_ | Format-List -Property * -Force | Out-String -Width 1000 | Write-Warning
Write-Verbose "Failed to obtain the component manifest from installCatalogUri provided via package parameters ($installCatalogUri). The component manifest will be loaded from the url supplied in the channel manifest (default behavior)."
}
}
}
if ($null -eq $ChannelManifest)
{
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 ($null -eq $url)
{
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
}
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 ($null -ne $localFile -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 ($null -eq $localFile)
{
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 ($null -ne $fileInLayout)
{
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
}
function Get-VSProductReference
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)] [PSObject] $ChannelReference,
[Parameter(Mandatory = $true)] [string] $Product,
[hashtable] $PackageParameters
)
$productId = $null
if ($null -ne $PackageParameters)
{
if ($PackageParameters.ContainsKey('productId'))
{
$productId = $PackageParameters['productId']
}
}
if ($null -eq $productId)
{
$productId = "Microsoft.VisualStudio.Product." + $Product
}
$obj = New-VSProductReference -ChannelId $ChannelReference.ChannelId -ProductId $ProductId -ChannelUri $ChannelReference.ChannelUri -InstallChannelUri $ChannelReference.InstallChannelUri
return $obj
}
function Get-VSProductVersionFromChannelManifest
{
[OutputType([System.Version])]
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)] [string] $ProductId,
[Parameter(Mandatory = $true)] [hashtable] $PackageParameters,
[PSObject] $ChannelReference,
[switch] $UseInstallChannelUri
)
Write-Verbose "Trying to determine the product $ProductId version 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'
$version = Get-VSChannelManifestItemVersion -Manifest $manifest -ChannelItemType 'ChannelProduct' -Id $ProductId
return $version
}
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
# VS 2022 17.4+
$version = Get-VSChannelManifestItemVersion -Manifest $channelManifest -ChannelItemType 'Bootstrapper' -PropertyName 'installerVersion'
if ($null -ne $version)
{
Write-Verbose "Required installer version determined from the channel manifest (as bootstrapper installerVersion property): '$version'"
}
else
{
# VS <= 2022 17.3
$version = Get-VSChannelManifestItemVersion -Manifest $channelManifest -ChannelItemType 'Bootstrapper' -PropertyName 'version'
if ($null -ne $version)
{
Write-Verbose "Required installer version determined from the channel manifest (as bootstrapper version property): '$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 ($null -ne $engineVersion)
{
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
}
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
}
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
}
# 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 ($null -ne $env:packageVersion) { $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 ($null -ne $Options -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
}
function Get-WillowInstalledProducts
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $false)] [string] $BasePath
)
Write-Debug 'Detecting Visual Studio products installed using the Willow installer (2017+)'
$loadedVsSetup = Get-Module -Name VSSetup
if (($loadedVsSetup | Measure-Object).Count -eq 0)
{
if ((Get-Module -Name VSSetup -ListAvailable | Measure-Object).Count -gt 0)
{
Write-Debug 'Importing the VSSetup module'
Import-Module -Name VSSetup
$loadedVsSetup = Get-Module -Name VSSetup
}
}
$hasVsSetup = $false
if ($null -ne $loadedVsSetup)
{
# check if VSSetup is at least 2.0 (which has prerelease VS support)
Write-Debug 'Checking version of VSSetup module'
if ($loadedVsSetup.Version.Major -ge 2)
{
Write-Debug "A supported VSSetup version is present ($($loadedVsSetup.Version))"
$hasVsSetup = $true
}
}
if ($hasVsSetup)
{
Write-Debug 'Using VSSetup to detect Visual Studio instances'
$instances = Get-VSSetupInstance -All -Prerelease
foreach ($instance in $instances)
{
if ($null -eq $instance)
{
continue
}
Write-Debug "Found product instance: $($instance.InstallationPath)"
$instancePackages = @{}
foreach ($package in $instance.Packages)
{
if ($null -eq $instance)
{
continue
}
$instancePackages[$package.Id] = $true
}
$instanceData = @{
installChannelUri = $null # Get-VSSetupInstance does not seem to provide it
channelUri = $instance.ChannelUri
channelId = $instance.ChannelId
nickname = $instance.Properties['nickname']
installationVersion = $instance.InstallationVersion
enginePath = $instance.EnginePath
productId = $instance.Product.Id
productLineVersion = $instance.CatalogInfo['ProductLineVersion']
installationPath = $instance.InstallationPath
selectedPackages = $instancePackages # in this case all installed, not only selected by the user
}
Write-Debug ('Instance data: {0}' -f (($instanceData.GetEnumerator() | Where-Object Key -ne 'selectedPackages' | ForEach-Object { '{0} = ''{1}''' -f $_.Key, $_.Value }) -join ' '))
Write-Debug ('Instance packages: {0}' -f ($instanceData.selectedPackages.Keys -join ' '))
Write-Output $instanceData
}
return
}
# If BasePath is specified, use it, otherwise look in the registry for the cache location
if ($BasePath -eq '')
{
# Package cache may have been moved, so check registry - https://blogs.msdn.microsoft.com/heaths/2017/04/17/moving-or-disabling-the-package-cache-for-visual-studio-2017/
$searchPath = @(
"HKLM:\SOFTWARE\Policies\Microsoft\VisualStudio\Setup",
"HKLM:\SOFTWARE\Microsoft\VisualStudio\Setup",
"HKLM:\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\Setup"
)
$cachePath = $searchPath | Get-ItemProperty -Name CachePath -ErrorAction SilentlyContinue | Select-Object -ExpandProperty CachePath -First 1
# If unable to locate the cache, try the default location
if ($null -ne $cachePath)
{
Write-Debug "Using VS CachePath obtained from registry: $cachePath"
}
else
{
$cachePath = "${Env:ProgramData}\Microsoft\VisualStudio\Packages"
Write-Debug "Using the default VS CachePath: $cachePath"
}
$BasePath = Join-Path -Path $cachePath -ChildPath '_Instances'
}
else
{
Write-Debug "Using provided BasePath: $BasePath"
}
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 ($null -eq $instanceDataPath)
{
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 ($null -eq $match -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
}
$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
}
}
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,
[hashtable] $DefaultParameterValues
)
if ($null -ne $Env:ChocolateyPackageDebug)
{
$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 -DefaultValues $DefaultParameterValues
$creatingLayout = $packageParameters.ContainsKey('layout')
$assumeNewVS2017Installer = $InstallerTechnology -eq 'WillowVS2017OrLater'
$channelReference = $null
$productReference = $null
if ($VisualStudioYear -ne '')
{
$channelReference = Get-VSChannelReference -VisualStudioYear $VisualStudioYear -Preview $Preview -PackageParameters $packageParameters
}
elseif ($packageParameters.ContainsKey('channelId'))
{
# Fallback for old packages, which did not specify VisualStudioYear.
# The actual year value passed here does not matter, because the function will use the channelId from package parameters.
$channelReference = Get-VSChannelReference -VisualStudioYear '2017' -Preview $Preview -PackageParameters $packageParameters
}
if ($null -ne $channelReference -and $Product -ne '')
{
if ($Product -ne '')
{
$productReference = Get-VSProductReference -ChannelReference $channelReference -Product $Product -PackageParameters $packageParameters
}
elseif ($packageParameters.ContainsKey('productId'))
{
# Fallback for old packages, which did not specify VisualStudioYear.
# The actual product name passed here does not matter, because the function will use the productId from package parameters.
$productReference = Get-VSProductReference -ChannelReference $channelReference -Product 'Ignored' -PackageParameters $packageParameters
}
}
if (-not $creatingLayout)
{
if ($assumeNewVS2017Installer)
{
# there is a single Programs and Features entry for all products, so its presence is not enough
if ($null -ne $productReference)
{
$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)
{
# Copy channel and product info back to package parameters. This helps packages which use the generic bootstrapper (vs_Setup.exe).
$packageParameters = $packageParameters.Clone()
if ($null -ne $channelReference)
{
if (-not $packageParameters.ContainsKey('channelId'))
{
$packageParameters['channelId'] = $channelReference.ChannelId
}
if (-not $packageParameters.ContainsKey('channelUri') -and -not [string]::IsNullOrEmpty($channelReference.ChannelUri))
{
$packageParameters['channelUri'] = $channelReference.ChannelUri
}
if (-not $packageParameters.ContainsKey('installChannelUri') -and -not [string]::IsNullOrEmpty($channelReference.InstallChannelUri))
{
$packageParameters['installChannelUri'] = $channelReference.InstallChannelUri
}
}
if ($null -ne $productReference)
{
if (-not $packageParameters.ContainsKey('productId'))
{
$packageParameters['productId'] = $productReference.ProductId
}
}
Assert-VSInstallerUpdated -PackageName $PackageName -PackageParameters $packageParameters -ChannelReference $channelReference -Url $Url -Checksum $Checksum -ChecksumType $ChecksumType -UseInstallChannelUri
if ($creatingLayout)
{
# vs_layout.exe (used internally by the VS Installer) does not support channel parameters on the command line (channelId, channelUri, installChannelUri), even though the docs suggest it should.
# Normally, those parameters are passed from a response file embedded inside the VS bootstrapper, so the values are hardwired to the origin of the bootstrapper.
# However, in some cases we want the flexibility to use a different channel, and in other cases we use a generic bootstrapper (vs_Setup.exe), which has a blank response file.
# Therefore, we need to remove those parameters from the command line and create our own response file (but only if the user did not pass their own!).
$channelParameters = @{}
foreach ($name in @('channelId', 'channelUri', 'installChannelUri'))
{
if ($packageParameters.ContainsKey($name))
{
Write-Debug "Layout: removing ${name} from command line parameters (value: '$($packageParameters[$name])')"
$channelParameters[$name] = $packageParameters[$name]
$packageParameters.Remove($name)
}
}
if ($channelParameters.Count -gt 0)
{
if (-not $packageParameters.ContainsKey('in'))
{
if ($channelParameters.ContainsKey('channelId') -and $channelParameters.ContainsKey('channelUri'))
{
$responseFilePath = Join-Path $Env:TEMP ('{0}_layout_{1:yyyyMMddHHmmss}.json' -f $PackageName, (Get-Date))
Write-Debug "Generating response file with path: $responseFilePath"
$responseFileContent = $channelParameters | ConvertTo-Json
Write-Debug "Response file content: $responseFileContent"
Set-Content -Path $responseFilePath -Value $responseFileContent -Encoding utf8
$packageParameters['in'] = $responseFilePath
}
else
{
# This should never happen with known VS packages, but someone somewhere may do something unexpected, so let's leave a hint in the logs.
Write-Verbose "When creating a layout, both channelId and channelUri should be provided if any of: channelId, channelUri, installChannelUri are."
}
}
else
{
Write-Debug "Some channel-related parameters were removed from the command line to the layout command, but a custom response file was passed via the --in parameter. In case of problems, please ensure the provided response file contains those parameters."
}
}
}
}
$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.'
}
}
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', '2022')] [string] $VisualStudioYear = '2017',
[switch] $Preview,
[switch] $Force,
[hashtable] $DefaultParameterValues
)
if ($null -ne $Env:ChocolateyPackageDebug)
{
$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 -DefaultValues $DefaultParameterValues
$channelReference = Get-VSChannelReference -VisualStudioYear $VisualStudioYear -Preview:$Preview -PackageParameters $packageParameters
$PSBoundParameters.Remove('VisualStudioYear')
$PSBoundParameters.Remove('Preview')
Install-VSInstaller -PackageParameters $packageParameters -ChannelReference $channelReference @PSBoundParameters
}
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 ($null -ne $Env:ChocolateyPackageDebug)
{
$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."
}
}
# 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
}
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,
[switch] $DoNotInstallIfNotPresent
)
Write-Debug "Running 'Install-VSInstaller' for $PackageName with Url:'$Url' Checksum:$Checksum ChecksumType:$ChecksumType RequiredInstallerVersion:'$RequiredInstallerVersion' RequiredEngineVersion:'$RequiredEngineVersion' Force:'$Force' UseInstallChannelUri:'$UseInstallChannelUri' DoNotInstallIfNotPresent:'$DoNotInstallIfNotPresent'";
$argumentSet = $PackageParameters.Clone()
Write-Debug 'Determining whether the Visual Studio Installer needs to be installed/updated/reinstalled'
$shouldUpdate = $false
$existing = Get-VisualStudioInstaller
if ($null -ne $existing)
{
Write-Debug 'The Visual Studio Installer is already present'
if ($null -ne $existing.Version -and $null -ne $RequiredInstallerVersion)
{
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 ($null -ne $existing.EngineVersion -and $null -ne $RequiredEngineVersion)
{
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
{
if ($DoNotInstallIfNotPresent)
{
Write-Debug 'The Visual Studio Installer is not present'
}
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 ($null -ne $existingHealth -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 ($null -ne $layoutPath)
{
$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 ($null -ne $env:packageVersion) { $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 ($null -eq $updated)
{
throw 'The Visual Studio Installer is not present even after supposedly successful update!'
}
if ($null -eq $existing)
{
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 ($null -ne $updated.Version)
{
if ($null -ne $RequiredInstallerVersion)
{
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 ($null -ne $updated.EngineVersion)
{
if ($null -ne $RequiredEngineVersion)
{
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)
}
function Merge-AdditionalArguments
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)] [hashtable] $Arguments,
[Parameter(Mandatory = $true)] [hashtable] $AdditionalArguments
)
foreach ($kvp in $AdditionalArguments.GetEnumerator())
{
$val = $kvp.Value
if ($null -ne $val)
{
# 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
}
}
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
}
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
}
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 ($null -eq $setupFolder -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 ($null -ne $isoPath)
{
$storageModule = Get-Module -ListAvailable -Name Storage
if ($null -eq $storageModule)
{
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 ($null -ne $setupFolder)
{
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 ($null -eq $installerFilePath)
{
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
}
# Parse input argument string into a hashtable
# Format: --AdminFile file location --Features WebTools,Win8SDK --ProductKey AB-D1
function Parse-Parameters
{
[CmdletBinding()]
Param (
[string] $s,
[hashtable] $DefaultValues
)
if ($null -ne $DefaultValues)
{
Write-Debug "Running 'Parse-Parameters' with s:'$s' DefaultValues:'$($DefaultValues.GetEnumerator() | ForEach-Object { $kvp = $_; $_.Value | ForEach-Object { '--{0} {1}' -f $kvp.Key, $_ } })'";
$parameters = $DefaultValues
}
else
{
Write-Debug "Running 'Parse-Parameters' with s:'$s' DefaultValues:''";
$parameters = @{}
}
$multiValuedParameterNames = @{ add = 1; remove = 1; addProductLang = 1; removeProductLang = 1; path = 1 }
[String[]] $kvpPrefix = @(" --")
$kvpDelimiter = ' '
$rxResetParameter = New-Object -TypeName System.Text.RegularExpressions.Regex -ArgumentList @('^reset-param(eter)?-(?=.)', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
if ($s -eq '')
{
Write-Debug "No package parameters."
$kvps = @()
}
else
{
Write-Debug "Package parameters: $s"
$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 ($rxResetParameter.IsMatch($key))
{
$resetParameterName = $rxResetParameter.Replace($key, '')
Write-Debug "Removing existing value of --$resetParameterName parameter, if any."
$parameters.Remove($resetParameterName)
}
elseif ($parameters.ContainsKey($key))
{
$existingValue = $parameters[$key]
if ($multiValuedParameterNames.ContainsKey($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
{
Write-Debug "Overwriting existing value of --$key parameter ('$existingValue') with '$value'."
$parameters[$key] = $value
}
}
else
{
$parameters.Add($key, $value)
}
}
# Convert "--path install=..." to --installPath, because other functions care about it.
if ($parameters.ContainsKey('path'))
{
$pathInstallValue = $null
$pathParameterValue = $parameters['path']
$rxInstallEquals = New-Object -TypeName System.Text.RegularExpressions.Regex -ArgumentList @('^install=(?=.)', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
if ($pathParameterValue -is [string] -and $rxInstallEquals.IsMatch($pathParameterValue))
{
Write-Debug "Found --path install=... in package parameters (as the only --path value), removing the --path parameter."
$pathInstallValue = $pathParameterValue
$parameters.Remove('path')
}
elseif ($pathParameterValue -is [System.Collections.IList])
{
$pathInstallValue = $pathParameterValue | Where-Object { $rxInstallEquals.IsMatch($_) } | Select-Object -Last 1
if ($null -ne $pathInstallValue)
{
Write-Debug "Found --path install=... in package parameters (among other --path values)."
$pathsWithoutInstall = @($pathParameterValue | Where-Object { -not $rxInstallEquals.IsMatch($_) })
$updatedPathsList = New-Object -TypeName System.Collections.Generic.List``1[System.String] -ArgumentList (,[string[]]($pathsWithoutInstall))
if ($updatedPathsList.Count -gt 1)
{
Write-Debug "Removing install=... from the list of --path values (remaining: $($updatedPathsList.Count))."
$parameters['path'] = $updatedPathsList
}
elseif ($updatedPathsList.Count -eq 1)
{
Write-Debug "Removing install=... from the list of --path values. Only 1 other --path value remains, so converting to scalar value."
$parameters['path'] = $updatedPathsList[0]
}
else
{
Write-Debug "No other values remain after removing install=... from the list of --path values, removing the --path parameter."
$parameters.Remove('path')
}
}
}
if ($null -ne $pathInstallValue)
{
$installPathValue = $rxInstallEquals.Replace($pathInstallValue, '')
Write-Debug "Converting [--path $pathInstallValue] to [--installPath $installPathValue]"
if ($parameters.ContainsKey('installPath'))
{
if ($parameters['installPath'] -ne $installPathValue)
{
Write-Error "Package parameters contain both '--installPath ...' and '--path install=...' with different values. Please provide one or the other, but not both. Provided installPath: [$($parameters['installPath'])]. provided path install=: [${installPathValue}]. Using the value of installPath."
$installPathValue = $parameters['installPath']
}
else
{
Write-Verbose "Package parameters contain both '--installPath ...' and '--path install=...' with the same values. For clarity, it is suggested to use one parameter or the other, but not both at the same time. The package will pass --installPath to the Visual Studio Installer."
}
}
$parameters['installPath'] = $installPathValue
}
}
return $parameters
}
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 ($null -eq $negativeSwitch)
{
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)
}
}
}
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,
[hashtable] $DefaultParameterValues
)
if ($null -ne $Env:ChocolateyPackageDebug)
{
$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")
$packageParameters = Parse-Parameters $env:chocolateyPackageParameters -DefaultValues $DefaultParameterValues
$channelReference = Get-VSChannelReference -VisualStudioYear $VisualStudioYear -Preview:$Preview -PackageParameters $packageParameters
Start-VSModifyOperation `
-PackageName $PackageName `
-PackageParameters $packageParameters `
-ArgumentList $argumentList `
-ChannelReference $channelReference `
-ApplicableProducts $ApplicableProducts `
-OperationTexts @('uninstalled', 'uninstalling', 'uninstallation')
}
function Remove-VisualStudioProduct
{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)] [string] $PackageName,
[Parameter(Mandatory = $true)] [string] $Product,
[Parameter(Mandatory = $true)] [string] $VisualStudioYear,
[bool] $Preview,
[hashtable] $DefaultParameterValues
)
if ($null -ne $Env:ChocolateyPackageDebug)
{
$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'";
$packageParameters = Parse-Parameters $env:chocolateyPackageParameters -DefaultValues $DefaultParameterValues
$channelReference = Get-VSChannelReference -VisualStudioYear $VisualStudioYear -Preview:$Preview -PackageParameters $packageParameters
$productReference = Get-VSProductReference -ChannelReference $channelReference -Product $Product -PackageParameters $packageParameters
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."
}
}
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,
[hashtable] $DefaultParameterValues
)
if ($null -ne $Env:ChocolateyPackageDebug)
{
$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")
$packageParameters = Parse-Parameters $env:chocolateyPackageParameters -DefaultValues $DefaultParameterValues
$channelReference = Get-VSChannelReference -VisualStudioYear $VisualStudioYear -Preview:$Preview -PackageParameters $packageParameters
Start-VSModifyOperation `
-PackageName $PackageName `
-PackageParameters $packageParameters `
-ArgumentList $argumentList `
-ChannelReference $channelReference `
-ApplicableProducts $ApplicableProducts `
-OperationTexts @('uninstalled', 'uninstalling', 'uninstallation')
}
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 ($null -eq $parameterToRemove)
{
continue
}
Write-Debug "Filtering out package parameter not passed to the ${TargetDescription}: '$parameterToRemove'"
$PackageParameters.Remove($parameterToRemove)
}
}
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
}
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)'
if ($null -ne $ProductReference)
{
Write-Debug "Detecting instances of VS products with ProductId = '$($ProductReference.ProductId)' ChannelId = '$($ProductReference.ChannelId)'"
$products = Get-WillowInstalledProducts | Where-Object { $null -ne $_ -and $_.channelId -eq $productReference.ChannelId -and $_.productId -eq $productReference.ProductId }
}
elseif ($null -ne $ChannelReference)
{
Write-Debug "Detecting instances of VS products with ChannelId = '$($ChannelReference.ChannelId)'"
$products = Get-WillowInstalledProducts | Where-Object { $null -ne $_ -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 { $null -ne $_ -and $_.installationPath -eq $installPath }
}
$count = ($products | Measure-Object).Count
Write-Debug "Resolved $count product instance(s)"
$products | Write-Output
}
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;
}
}
function Show-VSInstallerErrorLog
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)] [datetime] $Since,
[string] $LogPath = $Env:TEMP # note: choco.exe adjusts TEMP to realTEMP\chocolatey
)
Write-Verbose "Examining Visual Studio Installer log files (${LogPath}\dd_*.log)"
$installerLogs = @(Get-ChildItem -Path "${LogPath}\dd_installer_*.log" | Where-Object { $_.Length -gt 0 -and $_.LastWriteTime -gt $Since })
foreach ($installerLog in $installerLogs)
{
$installerLogPath = $installerLog.FullName
Write-Verbose "Found non-empty installer log: ${installerLogPath}"
$interestingLines = @($installerLog `
| Get-Content `
| Select-String '^[^\s]+\s(Warning|Error)' `
| Select-Object -ExpandProperty Line `
| Where-Object { $_ -notlike '*Skipping non-applicable package*' })
if (($interestingLines | Measure-Object).Count -gt 0)
{
Write-Warning "Errors/warnings from the Visual Studio Installer log file ${installerLogPath}:"
$interestingLines | Write-Warning
}
}
$errorLogs = @(Get-ChildItem -Path "${LogPath}\dd_*_errors.log" | Where-Object { $_.Length -gt 0 -and $_.LastWriteTime -gt $Since })
foreach ($errorLog in $errorLogs)
{
$errorLogPath = $errorLog.FullName
Write-Verbose "Found non-empty error log: ${errorLogPath}"
$matchingFullLogPath = $errorLogPath -replace '_errors\.log$', '.log'
if (Test-Path -Path $matchingFullLogPath)
{
$tailLines = 200 # determined empirically - should be enough to contain the interesting messages
$fullLogTail = Get-Content -Tail $tailLines -Path $matchingFullLogPath
Write-Verbose "Last $tailLines lines of Visual Studio Installer log file ${matchingFullLogPath}:"
$fullLogTail | Write-Verbose
}
Write-Warning "Content of Visual Studio Installer error log file ${errorLogPath}:"
$errorLog | Get-Content | Write-Warning
}
}
# 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),
[switch] $acceptAllExitCodes
)
Write-Debug "Running 'Start-VSChocolateyProcessAsAdmin' with exeToRun:'$exeToRun', statements:'$statements', minimized:$minimized, noSleep:$noSleep, validExitCodes:'$validExitCodes'";
$wrappedStatements = $statements
if ($null -eq $wrappedStatements) { $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 ($null -ne $EventArgs.Data) {
Write-Host "$($EventArgs.Data)"
}
}
$writeError = {
if ($null -ne $EventArgs.Data) {
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 (-not $acceptAllExitCodes -and $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
}
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,
[Parameter(Mandatory = $true)] [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 ($null -eq $ProductReference)
{
if ($PackageParameters.ContainsKey('productId'))
{
# Workload/component packages do not pass a ProductReference, because they may apply to several products.
# However, the user can explicitly narrow the operation scope via package parameters.
# The actual product name passed here does not matter, because the function will use the productId from package parameters.
$ProductReference = Get-VSProductReference -ChannelReference $channelReference -Product 'Ignored' -PackageParameters $packageParameters
}
elseif ($Operation -eq 'update')
{
throw 'ProductReference is mandatory for update operations.'
}
}
$frobbed, $frobbing, $frobbage = $OperationTexts
$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'))
{
$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 ($null -ne $ProductReference -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'])."
}
}
else
{
if (($ProductInstance | Measure-Object).Count -ne 0)
{
$installedProducts = $ProductInstance
}
else
{
if ($null -ne $ProductReference)
{
$installedProducts = Resolve-VSProductInstance -ProductReference $ProductReference -PackageParameters $PackageParameters
}
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 ($null -ne $RequiredProductVersion)
{
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')
{
if ($null -eq $DesiredProductVersion)
{
$firstProductId = $thisProductIds | Select-Object -First 1
Write-Verbose "DesiredProductVersion is not set, trying to obtain it from the channel manifest using product id $firstProductId"
$DesiredProductVersion = Get-VSProductVersionFromChannelManifest -ProductId $firstProductId -PackageParameters $PackageParameters -ChannelReference $ChannelReference
if ($null -ne $DesiredProductVersion)
{
Write-Verbose "Determined DesiredProductVersion from the channel manifest: $DesiredProductVersion"
}
else
{
Write-Verbose "Unable to determine DesiredProductVersion from the channel manifest. The script will not be able to determine the need for the update and to verify the update executed successfully."
}
}
if ($null -ne $DesiredProductVersion)
{
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)
{
# installPath should always be present
$productDescription = "Visual Studio product: [installPath = '$($argumentSet.installPath)']"
Write-Debug "Modifying $productDescription"
$thisProductReference = $ProductReference
if ($argumentSet.ContainsKey('__internal_productReference'))
{
$thisProductReference = $argumentSet['__internal_productReference']
$argumentSet.Remove('__internal_productReference')
}
$thisChannelReference = $ChannelReference
if ($null -ne $thisProductReference)
{
$thisChannelReference = Convert-VSProductReferenceToChannelReference -ProductReference $thisProductReference
}
$shouldFixInstaller = $false
if ($null -eq $installer)
{
$installer = Get-VisualStudioInstaller
if ($null -eq $installer)
{
$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 ($null -eq $installer)
{
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 some 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 ($null -ne $layoutPath)
{
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
if ($Operation -eq 'update')
{
# Remove arguments which cannot be used when updating an already installed VS instance.
# This supports users who turned on the 'useRememberedArgumentsForUpgrades' feature of Chocolatey.
# Reference: https://learn.microsoft.com/en-us/visualstudio/install/use-command-line-parameters-to-install-visual-studio?view=vs-2022#install-update-modify-repair-uninstall-and-export-commands-and-command-line-parameters
$argumentsNotForUpdate = @('add', 'remove', 'addProductLang', 'removeProductLang', 'all', 'allWorkloads', 'includeRecommended', 'includeOptional', 'nickname', 'productKey', 'config')
Remove-VSPackageParametersNotPassedToNativeInstaller -PackageParameters $argumentSet -TargetDescription "$nativeInstallerDescription for '$Operation' operation" -Blacklist $argumentsNotForUpdate
}
$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 ($null -ne $DesiredProductVersion)
{
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}."
}
}
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
)
$startTime = Get-Date
$exitCode = Start-VSChocolateyProcessAsAdmin -statements $silentArgs -exeToRun $file -acceptAllExitCodes
Write-Debug "Exit code returned from Start-VSChocolateyProcessAsAdmin: '$exitCode'"
if ($assumeNewVS2017Installer)
{
$auxExitCode = Wait-VSInstallerProcesses -Behavior 'Wait'
if ($null -ne $auxExitCode -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 (($successExitCodes | Measure-Object).Count -gt 0 -and $successExitCodes -contains $exitCode)
{
$needsReboot = $false
$success = $true
}
elseif (($rebootExitCodes | Measure-Object).Count -gt 0 -and $rebootExitCodes -contains $exitCode)
{
$needsReboot = $true
$success = $true
}
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 (($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."
}
}
}
else
{
$exceptionMessage = "The ${frobbage} of ${packageName} failed (installer exit code: ${exitCode})."
$success = $false
}
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 | Measure-Object).Count -gt 0)
{
$warnings | Write-Warning
}
if ($assumeNewVS2017Installer)
{
Show-VSInstallerErrorLog -Since $startTime
}
throw $exceptionMessage
}
}
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 ($null -ne $Env:ChocolateyPackageDebug)
{
$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 ($null -eq $vsInstaller)
{
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
$supportsNoRestart = $vsInstaller.Traits -contains 'SelfUninstallNoRestart'
}
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"
$supportsNoRestart = $true
}
$silentArgs = Generate-UninstallArgumentsString -parameters $packageParameters -logFilePath $logFilePath -assumeNewVS2017Installer:$assumeNewVS2017Installer -supportsNoRestart:$supportsNoRestart
$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
}
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 ($null -ne $Env:ChocolateyPackageDebug)
{
$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."
}
}
# 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')
}
# 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 ($null -ne $node)
{
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)
}
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 { $null -ne $_ -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', 'setup')
$vsInstallerProcessFilter = { $_.Name -ne 'setup' -or $_.Path -like '*\Microsoft Visual Studio\Installer*\setup.exe' }
do
{
$vsInstallerProcesses = Get-Process -Name $vsInstallerProcessNames -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ -and -not $_.HasExited } | Where-Object $vsInstallerProcessFilter
$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 ($null -eq $exitCode)
{
$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 $null -ne $proc.ExitCode)
{
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 { $null -ne $_ -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 ($null -eq $exitCode)
{
$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 $null -ne $proc.ExitCode)
{
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
}
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.
© 2017-2023 Jakub Bereżański
This package has no dependencies.
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.