Welcome to the Chocolatey Community Package Repository! The packages found in this section of the site are provided, maintained, and moderated by the community.
Moderation
Every version of each package undergoes a rigorous moderation process before it goes live that typically includes:
- Security, consistency, and quality checking
- Installation testing
- Virus checking through VirusTotal
- Human moderators who give final review and sign off
More detail at Security and Moderation.
Organizational Use
If you are an organization using Chocolatey, we want your experience to be fully reliable. Due to the nature of this publicly offered repository, reliability cannot be guaranteed. Packages offered here are subject to distribution rights, which means they may need to reach out further to the internet to the official locations to download files at runtime.
Fortunately, distribution rights do not apply for internal use. With any edition of Chocolatey (including the free open source edition), you can host your own packages and cache or internalize existing community packages.
Disclaimer
Your use of the packages on this site means you understand they are not supported or guaranteed in any way. Learn more...
-
STEP1
Package Review
-
STEP2
Integration Method
-
STEP3
Internal Repo Url
-
STEP4
Environment Setup
-
STEP5
Install Script
Step 1: Review Your Packages
Step 2: Choose Your Integration Method
Step 3: Enter Your Internal Repository Url
(this should look similar to https://community.chocolatey.org/api/v2/)
Step 3: Copy Your Script or Download Config
Option 1: Copy Script
Option 2: Download Config
Step 4: 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 packages and push them to a repository
Download Packages
-
Open Source
-
Download the packages:
Download Packages - Follow manual internalization instructions
-
-
Package Internalizer (C4B)
-
Run: (additional options)
-
For package and dependencies run:
- Automate package internalization
-
Run: (additional options)
Step 5: Copy Your Script
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:
## 1. REQUIREMENTS ##
### Here are the requirements necessary to ensure this is successful.
### a. Internal/Private Cloud Repository Set Up ###
#### You'll need an internal/private cloud repository you can use. These are
#### generally really quick to set up and there are quite a few options.
#### Chocolatey Software recommends Nexus, Artifactory Pro, or ProGet as they
#### are repository servers and will give you the ability to manage multiple
#### repositories and types from one server installation.
### b. Download Chocolatey Package and Put on Internal Repository ###
#### You need to have downloaded the Chocolatey package as well.
#### Please see https://chocolatey.org/install#organization
### c. Other Requirements ###
#### We initialize a few things that are needed by this script - there are no other requirements.
$ErrorActionPreference = "Stop"
#### Set TLS 1.2 (3072) as that is the minimum required by various up-to-date repositories.
#### Use integers because the enumeration value for TLS 1.2 won't exist
#### in .NET 4.0, even though they are addressable if .NET 4.5+ is
#### installed (.NET 4.5 is an in-place upgrade).
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
#### We use this variable for future REST calls.
$RequestArguments = @{
UseBasicParsing = $true
}
## 2. TOP LEVEL VARIABLES ##
### a. Your internal repository url (the main one). ###
#### Should be similar to what you see when you browse
#### to https://community.chocolatey.org/api/v2/
$NugetRepositoryUrl = "INTERNAL REPO URL"
### b. Internal Repository Credential ###
#### If required, add the repository access credential here
# $NugetRepositoryCredential = [PSCredential]::new(
# "username",
# ("password" | ConvertTo-SecureString -AsPlainText -Force)
# )
# $RequestArguments.Credential = $NugetRepositoryCredential
### c. Chocolatey nupkg download url ###
#### This url should result in an immediate download when you navigate to it
$ChocolateyDownloadUrl = "$($NugetRepositoryUrl.TrimEnd('/'))/package/chocolatey.1.1.0.nupkg"
### d. Chocolatey Central Management (CCM) ###
#### If using CCM to manage Chocolatey, add the following:
#### i. Endpoint URL for CCM
# $ChocolateyCentralManagementUrl = "https://chocolatey-central-management:24020/ChocolateyManagementService"
#### ii. If using a Client Salt, add it here
# $ChocolateyCentralManagementClientSalt = "clientsalt"
#### iii. If using a Service Salt, add it here
# $ChocolateyCentralManagementServiceSalt = "servicesalt"
## 3. ENSURE CHOCOLATEY IS INSTALLED ##
### Ensure Chocolatey is installed from your internal repository
#### Download the Nupkg, appending .zip to the filename to handle archive cmdlet limitations
if (-not (Get-Command choco.exe -ErrorAction SilentlyContinue)) {
$TempDirectory = Join-Path $env:Temp "chocolateyInstall"
if (-not (Test-Path $TempDirectory -PathType Container)) {
$null = New-Item -Path $TempDirectory -ItemType Directory
}
$DownloadedNupkg = Join-Path $TempDirectory "$(Split-Path $ChocolateyDownloadUrl -Leaf).zip"
Invoke-WebRequest -Uri $ChocolateyDownloadUrl -OutFile $DownloadedNupkg @RequestArguments
#### Extract the Nupkg, and run the chocolateyInstall script
if (Get-Command Microsoft.PowerShell.Archive\Expand-Archive -ErrorAction SilentlyContinue) {
Microsoft.PowerShell.Archive\Expand-Archive -Path $DownloadedNupkg -DestinationPath $TempDirectory -Force
} else {
# PowerShell versions <4.0 do not have this function available
try {
$shellApplication = New-Object -ComObject Shell.Application
$zipPackage = $shellApplication.NameSpace($DownloadedNupkg)
$destinationFolder = $shellApplication.NameSpace($TempDirectory)
$destinationFolder.CopyHere($zipPackage.Items(), 0x10)
} catch {
Write-Warning "Unable to unzip package using built-in compression."
throw $_
}
}
& $(Join-Path $TempDirectory "tools\chocolateyInstall.ps1")
}
if (-not (Get-Command choco.exe -ErrorAction SilentlyContinue)) {
refreshenv
}
## 4. CONFIGURE CHOCOLATEY BASELINE ##
### a. FIPS Feature ###
#### If you need FIPS compliance - make this the first thing you configure
#### before you do any additional configuration or package installations
# choco feature enable -n useFipsCompliantChecksums
### b. Apply Recommended Configuration ###
#### Move cache location so Chocolatey is very deterministic about
#### cleaning up temporary data and the location is secured to admins
choco config set --name cacheLocation --value C:\ProgramData\chocolatey\cache
#### Increase timeout to at least 4 hours
choco config set --name commandExecutionTimeoutSeconds --value 14400
#### Turn off download progress when running choco through integrations
choco feature disable --name showDownloadProgress
### c. Sources ###
#### Remove the default community package repository source
choco source list --limitoutput | ConvertFrom-Csv -Header 'Name', 'Location' -Delimiter '|' | ForEach-Object {
if ($_.Location -eq 'https://community.chocolatey.org/api/v2/') {
choco source remove -n $_.Name
}
}
#### Add internal default sources
#### You could have multiple sources here, so we will provide an example
#### of one using the remote repo variable here
#### NOTE: This EXAMPLE may require changes
if ($NugetRepositoryCredential) {
choco source add --name ChocolateyInternal --source $NugetRepositoryUrl --user $NugetRepositoryCredential.UserName --password $NugetRepositoryCredential.GetNetworkCredential().Password --priority 1
} else {
choco source add --name ChocolateyInternal --source $NugetRepositoryUrl --priority 1
}
### b. Keep Chocolatey Up To Date ###
#### Keep chocolatey up to date based on your internal source
#### You control the upgrades based on when you push an updated version
#### to your internal repository.
#### Note the source here is to the OData feed, similar to what you see
#### when you browse to https://community.chocolatey.org/api/v2/
choco upgrade chocolatey --confirm
## 5. ENSURE CHOCOLATEY FOR BUSINESS ##
### If you don't have Chocolatey for Business (C4B), you'll want to remove from here down.
### a. Ensure The License File Is Installed ###
#### Create a license package using script from https://docs.chocolatey.org/en-us/how-tos/setup-offline-installation#exercise-4-create-a-package-for-the-license
choco install chocolatey-license --source $NugetRepositoryUrl --confirm
### b. Disable The Licensed Source ###
#### The licensed source cannot be removed, so it must be disabled.
#### This must occur after the license has been set by the license package.
if ("chocolatey-license" -in (choco list --localonly --limitoutput | ConvertFrom-Csv -Header "Name" -Delimiter "|").Name) {
choco source disable --name chocolatey.licensed
} else {
Write-Warning "Not disabling 'chocolatey.licensed' feed, as Chocolatey-License has not been installed."
}
### c. Ensure Chocolatey Licensed Extension ###
#### You will have downloaded the licensed extension to your internal repository
#### as you have disabled the licensed repository in step 5b.
#### Ensure the chocolatey.extension package (aka Chocolatey Licensed Extension)
if ("chocolatey-license" -in (choco list --localonly --limitoutput | ConvertFrom-Csv -Header "Name" -Delimiter "|").Name) {
choco install chocolatey.extension --source $NugetRepositoryUrl --confirm
} else {
Write-Warning "Not installing 'chocolatey.extension', as Chocolatey-License has not been installed."
}
#### The Chocolatey Licensed Extension unlocks all of the following, which also have configuration/feature items available with them. You may want to visit the feature pages to see what you might want to also enable:
#### - Package Builder - https://docs.chocolatey.org/en-us/features/paid/package-builder
#### - Package Internalizer - https://docs.chocolatey.org/en-us/features/paid/package-internalizer
#### - Package Synchronization (3 components) - https://docs.chocolatey.org/en-us/features/paid/package-synchronization
#### - Package Reducer - https://docs.chocolatey.org/en-us/features/paid/package-reducer
#### - Package Audit - https://docs.chocolatey.org/en-us/features/paid/package-audit
#### - Package Throttle - https://docs.chocolatey.org/en-us/features/paid/package-throttle
#### - CDN Cache Access - https://docs.chocolatey.org/en-us/features/paid/private-cdn
#### - Branding - https://docs.chocolatey.org/en-us/features/paid/branding
#### - Self-Service Anywhere (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/self-service-anywhere
#### - Chocolatey Central Management (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/chocolatey-central-management
#### - Other - https://docs.chocolatey.org/en-us/features/paid/
### d. Ensure Self-Service Anywhere ###
#### If you have desktop clients where users are not administrators, you may
#### to take advantage of deploying and configuring Self-Service anywhere
choco feature disable --name showNonElevatedWarnings
choco feature enable --name useBackgroundService
choco feature enable --name useBackgroundServiceWithNonAdministratorsOnly
choco feature enable --name allowBackgroundServiceUninstallsFromUserInstallsOnly
choco config set --name allowedBackgroundServiceCommands --value "install,upgrade,uninstall"
### e. Ensure Chocolatey Central Management ###
#### If you want to manage and report on endpoints, you can set up and configure
### Central Management. There are multiple portions to manage, so you'll see
### a section on agents here along with notes on how to configure the server
### side components.
if ($ChocolateyCentralManagementUrl) {
choco install chocolatey-agent --source $NugetRepositoryUrl --confirm
choco config set --name CentralManagementServiceUrl --value $ChocolateyCentralManagementUrl
if ($ChocolateyCentralManagementClientSalt) {
choco config set --name centralManagementClientCommunicationSaltAdditivePassword --value $ChocolateyCentralManagementClientSalt
}
if ($ChocolateyCentralManagementServiceSalt) {
choco config set --name centralManagementServiceCommunicationSaltAdditivePassword --value $ChocolateyCentralManagementServiceSalt
}
choco feature enable --name useChocolateyCentralManagement
choco feature enable --name useChocolateyCentralManagementDeployments
}
See docs at https://docs.ansible.com/ansible/latest/modules/win_chocolatey_module.html.
If Applicable - Chocolatey Configuration/Installation
## 1. REQUIREMENTS ##
### Here are the requirements necessary to ensure this is successful.
### a. Internal/Private Cloud Repository Set Up ###
#### You'll need an internal/private cloud repository you can use. These are
#### generally really quick to set up and there are quite a few options.
#### Chocolatey Software recommends Nexus, Artifactory Pro, or ProGet as they
#### are repository servers and will give you the ability to manage multiple
#### repositories and types from one server installation.
### b. Download Chocolatey Package and Put on Internal Repository ###
#### You need to have downloaded the Chocolatey package as well.
#### Please see https://chocolatey.org/install#organization
### c. Other Requirements ###
#### i. chocolatey.chocolatey
##### You will require the chocolatey.chocolatey collection to be installed
##### on all machines using this playbook.
##### Please see https://github.com/chocolatey/chocolatey-ansible/#installing-the-collection-from-ansible-galaxy
- name: Install and Configure Chocolatey
hosts: all
## 2. TOP LEVEL VARIABLES ##
vars:
### a. Your internal repository url (the main one). ###
#### Should be similar to what you see when you browse
#### to https://community.chocolatey.org/api/v2/
nuget_repository_url: INTERNAL REPO URL
### b. Internal Repository Credential ###
#### If required, add the repository access credential here and
#### uncomment lines with source_username and source_password below
# nuget_repository_username: username
# nuget_repository_password: password
### c. Chocolatey Central Management (CCM) ###
#### If using CCM to manage Chocolatey, add the following:
#### i. Endpoint URL for CCM
# chocolatey_central_management_url: https://chocolatey-central-management:24020/ChocolateyManagementService
#### ii. If using a Client Salt, add it here
# chocolatey_central_management_client_salt: clientsalt
#### iii. If using a Service Salt, add it here
# chocolatey_central_management_service_salt: servicesalt
## 3. ENSURE CHOCOLATEY IS INSTALLED ##
### Ensure Chocolatey is installed from your internal repository
tasks:
- name: Install chocolatey
win_chocolatey:
name: chocolatey
source: {{ nuget_repository_url }}
# source_username: {{ nuget_repository_username }}
# source_password: {{ nuget_repository_password }}
## 4. CONFIGURE CHOCOLATEY BASELINE ##
### a. FIPS Feature ###
#### If you need FIPS compliance - make this the first thing you configure
#### before you do any additional configuration or package installations
# - name: Enable FIPS compliance
# win_chocolatey_feature:
# name: useFipsCompliantChecksums
# state: enabled
### b. Apply Recommended Configuration ###
#### Move cache location so Chocolatey is very deterministic about
#### cleaning up temporary data and the location is secured to admins
- name: Set the cache location
win_chocolatey_config:
name: cacheLocation
state: present
value: C:\ProgramData\chocolatey\cache
#### Increase timeout to at least 4 hours
- name: Set the command execution timeout
win_chocolatey_config:
name: commandExecutionTimeoutSeconds
state: present
value: 14400
#### Turn off download progress when running choco through integrations
- name: Disable showing download progress
win_chocolatey_feature:
name: showDownloadProgress
state: disabled
### c. Sources ###
#### Remove the default community package repository source
- name: Remove Chocolatey Community Repository
win_chocolatey_source:
name: chocolatey
state: absent
#### Add internal default sources
#### You could have multiple sources here, so we will provide an example
#### of one using the remote repo variable here
#### NOTE: This EXAMPLE may require changes
- name: Add Internal Repository
win_chocolatey_source:
name: ChocolateyInternal
state: present
source: {{ nuget_repository_url }}
# source_username: {{ nuget_repository_username }}
# source_password: {{ nuget_repository_password }}
priority: 1
### b. Keep Chocolatey Up To Date ###
#### Keep chocolatey up to date based on your internal source
#### You control the upgrades based on when you push an updated version
#### to your internal repository.
#### Note the source here is to the OData feed, similar to what you see
#### when you browse to https://community.chocolatey.org/api/v2/
- name: Upgrade Chocolatey
win_chocolatey:
name: chocolatey
state: latest
## 5. ENSURE CHOCOLATEY FOR BUSINESS ##
### If you don't have Chocolatey for Business (C4B), you'll want to remove from here down.
### a. Ensure The License File Is Installed ###
#### Create a license package using script from https://docs.chocolatey.org/en-us/how-tos/setup-offline-installation#exercise-4-create-a-package-for-the-license
- name: Install Chocolatey License
win_chocolatey:
name: chocolatey-license
source: ChocolateyInternal
state: latest
### b. Disable The Licensed Source ###
#### The licensed source cannot be removed, so it must be disabled.
#### This must occur after the license has been set by the license package.
- name: Disable Chocolatey Community Repository
win_chocolatey_source:
name: chocolatey.licensed
state: disabled
### c. Ensure Chocolatey Licensed Extension ###
#### You will have downloaded the licensed extension to your internal repository
#### as you have disabled the licensed repository in step 5b.
#### Ensure the chocolatey.extension package (aka Chocolatey Licensed Extension)
- name: Install Chocolatey Extension
win_chocolatey:
name: chocolatey.extension
source: ChocolateyInternal
state: latest
#### The Chocolatey Licensed Extension unlocks all of the following, which also have configuration/feature items available with them. You may want to visit the feature pages to see what you might want to also enable:
#### - Package Builder - https://docs.chocolatey.org/en-us/features/paid/package-builder
#### - Package Internalizer - https://docs.chocolatey.org/en-us/features/paid/package-internalizer
#### - Package Synchronization (3 components) - https://docs.chocolatey.org/en-us/features/paid/package-synchronization
#### - Package Reducer - https://docs.chocolatey.org/en-us/features/paid/package-reducer
#### - Package Audit - https://docs.chocolatey.org/en-us/features/paid/package-audit
#### - Package Throttle - https://docs.chocolatey.org/en-us/features/paid/package-throttle
#### - CDN Cache Access - https://docs.chocolatey.org/en-us/features/paid/private-cdn
#### - Branding - https://docs.chocolatey.org/en-us/features/paid/branding
#### - Self-Service Anywhere (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/self-service-anywhere
#### - Chocolatey Central Management (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/chocolatey-central-management
#### - Other - https://docs.chocolatey.org/en-us/features/paid/
### d. Ensure Self-Service Anywhere ###
#### If you have desktop clients where users are not administrators, you may
#### to take advantage of deploying and configuring Self-Service anywhere
- name: Hide not-elevated warnings
win_chocolatey_feature:
name: showNonElevatedWarnings
state: disabled
- name: Use background mode for self-service
win_chocolatey_feature:
name: useBackgroundService
state: enabled
- name: Use background service for non-admins
win_chocolatey_feature:
name: useBackgroundServiceWithNonAdministratorsOnly
state: enabled
- name: Allow background uninstallation for user installs
win_chocolatey_feature:
name: allowBackgroundServiceUninstallsFromUserInstallsOnly
state: enabled
- name: Set allowed background service commands
win_chocolatey_config:
name: backgroundServiceAllowedCommands
state: present
value: install,upgrade,uninstall
### e. Ensure Chocolatey Central Management ###
#### If you want to manage and report on endpoints, you can set up and configure
### Central Management. There are multiple portions to manage, so you'll see
### a section on agents here along with notes on how to configure the server
### side components.
- name: Install Chocolatey Agent
when: chocolatey_central_management_url is defined
win_chocolatey:
name: chocolatey-agent
source: ChocolateyInternal
state: latest
- name: Set the Central Management Service URL
when: chocolatey_central_management_url is defined
win_chocolatey_config:
name: CentralManagementServiceUrl
state: present
value: {{ chocolatey_central_management_url }}
- name: Set the Central Management Client Salt
when: chocolatey_central_management_client_salt is defined
win_chocolatey_config:
name: centralManagementClientCommunicationSaltAdditivePassword
state: present
value: {{ chocolatey_central_management_client_salt }}
- name: Set the Central Management Service Salt
when: chocolatey_central_management_service_salt is defined
win_chocolatey_config:
name: centralManagementServiceCommunicationSaltAdditivePassword
state: present
value: {{ chocolatey_central_management_service_salt }}
- name: Use Central Management
when: chocolatey_central_management_url is defined
win_chocolatey_feature:
name: useChocolateyCentralManagement
state: enabled
- name: Use Central Management Deployments
when: chocolatey_central_management_url is defined
win_chocolatey_feature:
name: useChocolateyCentralManagementDeployments
state: enabled
See docs at https://docs.chef.io/resource_chocolatey_package.html.
If Applicable - Chocolatey Configuration/Installation
## 1. REQUIREMENTS ##
### Here are the requirements necessary to ensure this is successful.
### a. Internal/Private Cloud Repository Set Up ###
#### You'll need an internal/private cloud repository you can use. These are
#### generally really quick to set up and there are quite a few options.
#### Chocolatey Software recommends Nexus, Artifactory Pro, or ProGet as they
#### are repository servers and will give you the ability to manage multiple
#### repositories and types from one server installation.
### b. Download Chocolatey Package and Put on Internal Repository ###
#### You need to have downloaded the Chocolatey package as well.
#### Please see https://chocolatey.org/install#organization
### c. Other Requirements ###
#### The Chocolatey resources are available with any recent version of Chef.
#### We utilise the Chocolatey recipe to install the Chocolatey binaries.
include_recipe "chocolatey"
## 2. TOP LEVEL VARIABLES ##
### a. Your internal repository url (the main one). ###
#### Should be similar to what you see when you browse
#### to https://community.chocolatey.org/api/v2/
NugetRepositoryUrl = "INTERNAL REPO URL"
### b. Internal Repository Credential ###
#### If required, add the repository access credential here
# NugetRepositoryUsername = "username"
# NugetRepositoryPassword = "password"
### c. Chocolatey nupkg download url ###
#### This url should result in an immediate download when you navigate to it in
#### a web browser
ChocolateyNupkgUrl = "INTERNAL REPO URL/package/chocolatey.1.1.0.nupkg",
### d. Chocolatey Central Management (CCM) ###
#### If using CCM to manage Chocolatey, add the following:
#### i. Endpoint URL for CCM
# ChocolateyCentralManagementUrl = "https://chocolatey-central-management:24020/ChocolateyManagementService"
#### ii. If using a Client Salt, add it here
# ChocolateyCentralManagementClientSalt = "clientsalt"
#### iii. If using a Service Salt, add it here
# ChocolateyCentralManagementServiceSalt = "servicesalt"
## 3. ENSURE CHOCOLATEY IS INSTALLED ##
### Ensure Chocolatey is installed from your internal repository
node['chocolatey']['install vars'] = {
'chocolateyDownloadUrl' => "#{ChocolateyNupkgUrl}",
}
## 4. CONFIGURE CHOCOLATEY BASELINE ##
### a. FIPS Feature ###
#### If you need FIPS compliance - make this the first thing you configure
#### before you do any additional configuration or package installations
# chocolatey_feature 'useFipsCompliantChecksums' do
# action :enable
# end
### b. Apply Recommended Configuration ###
#### Move cache location so Chocolatey is very deterministic about
#### cleaning up temporary data and the location is secured to admins
chocolatey_config 'cacheLocation' do
value 'C:\ProgramData\chocolatey\cache'
end
#### Increase timeout to at least 4 hours
chocolatey_config 'commandExecutionTimeoutSeconds' do
value '14400'
end
#### Turn off download progress when running choco through integrations
chocolatey_feature 'showDownloadProgress' do
action :disable
end
### c. Sources ###
#### Remove the default community package repository source
chocolatey_source 'chocolatey' do
action :remove
end
#### Add internal default sources
#### You could have multiple sources here, so we will provide an example
#### of one using the remote repo variable here
#### NOTE: This EXAMPLE may require changes
chocolatey_source 'ChocolateyInternal' do
source "#{NugetRepositoryUrl}"
priority 1
action :add
end
execute 'ChocolateyInternal' do
command "choco source add --name ChocolateyInternal -s #{NugetRepositoryUrl} -u=#{NugetRepositoryUsername} -p=#{NugetRepositoryPassword} --priority=1"
only_if { NugetRepositoryUsername != nil || NugetRepositoryPassword != nil }
end
### b. Keep Chocolatey Up To Date ###
#### Keep chocolatey up to date based on your internal source
#### You control the upgrades based on when you push an updated version
#### to your internal repository.
#### Note the source here is to the OData feed, similar to what you see
#### when you browse to https://community.chocolatey.org/api/v2/
chocolatey_package 'chocolatey' do
action :upgrade
source "#{NugetRepositoryUrl}"
end
## 5. ENSURE CHOCOLATEY FOR BUSINESS ##
### If you don't have Chocolatey for Business (C4B), you'll want to remove from here down.
### a. Ensure The License File Is Installed ###
#### Create a license package using script from https://docs.chocolatey.org/en-us/how-tos/setup-offline-installation#exercise-4-create-a-package-for-the-license
chocolatey_package 'chocolatey-license' do
action :install
source "#{NugetRepositoryUrl}"
end
### b. Disable The Licensed Source ###
#### The licensed source cannot be removed, so it must be disabled.
#### This must occur after the license has been set by the license package.
chocolatey_source 'chocolatey.licensed' do
action :disable
end
### c. Ensure Chocolatey Licensed Extension ###
#### You will have downloaded the licensed extension to your internal repository
#### as you have disabled the licensed repository in step 5b.
#### Ensure the chocolatey.extension package (aka Chocolatey Licensed Extension)
chocolatey_package 'chocolatey.extention' do
action install
source "#{NugetRepositoryUrl}"
end
#### The Chocolatey Licensed Extension unlocks all of the following, which also have configuration/feature items available with them. You may want to visit the feature pages to see what you might want to also enable:
#### - Package Builder - https://docs.chocolatey.org/en-us/features/paid/package-builder
#### - Package Internalizer - https://docs.chocolatey.org/en-us/features/paid/package-internalizer
#### - Package Synchronization (3 components) - https://docs.chocolatey.org/en-us/features/paid/package-synchronization
#### - Package Reducer - https://docs.chocolatey.org/en-us/features/paid/package-reducer
#### - Package Audit - https://docs.chocolatey.org/en-us/features/paid/package-audit
#### - Package Throttle - https://docs.chocolatey.org/en-us/features/paid/package-throttle
#### - CDN Cache Access - https://docs.chocolatey.org/en-us/features/paid/private-cdn
#### - Branding - https://docs.chocolatey.org/en-us/features/paid/branding
#### - Self-Service Anywhere (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/self-service-anywhere
#### - Chocolatey Central Management (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/chocolatey-central-management
#### - Other - https://docs.chocolatey.org/en-us/features/paid/
### d. Ensure Self-Service Anywhere ###
#### If you have desktop clients where users are not administrators, you may
#### to take advantage of deploying and configuring Self-Service anywhere
chocolatey_feature 'showNonElevatedWarnings' do
action :disable
end
chocolatey_feature 'useBackgroundService' do
action :enable
end
chocolatey_feature 'useBackgroundServiceWithNonAdministratorsOnly' do
action :enable
end
chocolatey_feature 'allowBackgroundServiceUninstallsFromUserInstallsOnly' do
action :enable
end
chocolatey_config 'backgroundServiceAllowedCommands' do
value 'install,upgrade,uninstall'
end
### e. Ensure Chocolatey Central Management ###
#### If you want to manage and report on endpoints, you can set up and configure
### Central Management. There are multiple portions to manage, so you'll see
### a section on agents here along with notes on how to configure the server
### side components.
chocolatey_package 'chocolatey-agent' do
action install
source "#{NugetRepositoryUrl}"
# user "#{NugetRepositoryUsername}"
# password "#{NugetRepositoryPassword}"
only_if { ChocolateyCentralManagementUrl != nil }
end
chocolatey_config 'CentralManagementServiceUrl' do
value "#{ChocolateyCentralManagementUrl}"
only_if { ChocolateyCentralManagementUrl != nil }
end
chocolatey_config 'centralManagementClientCommunicationSaltAdditivePassword' do
value "#{ChocolateyCentralManagementClientSalt}"
only_if { ChocolateyCentralManagementClientSalt != nil }
end
chocolatey_config 'centralManagementServiceCommunicationSaltAdditivePassword' do
value "#{ChocolateyCentralManagementServiceSalt}"
only_if { ChocolateyCentralManagementServiceSalt != nil }
end
chocolatey_feature 'useChocolateyCentralManagement' do
action :enable
only_if { ChocolateyCentralManagementUrl != nil }
end
chocolatey_feature 'useChocolateyCentralManagementDeployments' do
action :enable
only_if { ChocolateyCentralManagementUrl != nil }
end
Requires cChoco DSC Resource. See docs at https://github.com/chocolatey/cChoco.
If Applicable - Chocolatey Configuration/Installation
#requires -Modules cChoco
## 1. REQUIREMENTS ##
### Here are the requirements necessary to ensure this is successful.
### a. Internal/Private Cloud Repository Set Up ###
#### You'll need an internal/private cloud repository you can use. These are
#### generally really quick to set up and there are quite a few options.
#### Chocolatey Software recommends Nexus, Artifactory Pro, or ProGet as they
#### are repository servers and will give you the ability to manage multiple
#### repositories and types from one server installation.
### b. Download Chocolatey Package and Put on Internal Repository ###
#### You need to have downloaded the Chocolatey package as well.
#### Please see https://chocolatey.org/install#organization
### c. Other Requirements ###
#### i. Requires chocolatey\cChoco DSC module to be installed on the machine compiling the DSC manifest
#### NOTE: This will need to be installed before running the DSC portion of this script
if (-not (Get-Module cChoco -ListAvailable)) {
$null = Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
if (($PSGallery = Get-PSRepository -Name PSGallery).InstallationPolicy -ne "Trusted") {
Set-PSRepository -Name PSGallery -InstallationPolicy Trusted
}
Install-Module -Name cChoco
if ($PSGallery.InstallationPolicy -ne "Trusted") {
Set-PSRepository -Name PSGallery -InstallationPolicy $PSGallery.InstallationPolicy
}
}
#### ii. Requires a hosted copy of the install.ps1 script
##### This should be available to download without authentication.
##### The original script can be found here: https://community.chocolatey.org/install.ps1
Configuration ChocolateyConfig {
## 2. TOP LEVEL VARIABLES ##
param(
### a. Your internal repository url (the main one). ###
#### Should be similar to what you see when you browse
#### to https://community.chocolatey.org/api/v2/
$NugetRepositoryUrl = "INTERNAL REPO URL",
### b. Chocolatey nupkg download url ###
#### This url should result in an immediate download when you navigate to it in
#### a web browser
$ChocolateyNupkgUrl = "INTERNAL REPO URL/package/chocolatey.1.1.0.nupkg",
### c. Internal Repository Credential ###
#### If required, add the repository access credential here
# $NugetRepositoryCredential = [PSCredential]::new(
# "username",
# ("password" | ConvertTo-SecureString -AsPlainText -Force)
# ),
### d. Install.ps1 URL
#### The path to the hosted install script:
$ChocolateyInstallPs1Url = "https://community.chocolatey.org/install.ps1"
### e. Chocolatey Central Management (CCM) ###
#### If using CCM to manage Chocolatey, add the following:
#### i. Endpoint URL for CCM
# $ChocolateyCentralManagementUrl = "https://chocolatey-central-management:24020/ChocolateyManagementService",
#### ii. If using a Client Salt, add it here
# $ChocolateyCentralManagementClientSalt = "clientsalt",
#### iii. If using a Service Salt, add it here
# $ChocolateyCentralManagementServiceSalt = "servicesalt"
)
Import-DscResource -ModuleName PSDesiredStateConfiguration
Import-DscResource -ModuleName cChoco
Node 'localhost' {
## 3. ENSURE CHOCOLATEY IS INSTALLED ##
### Ensure Chocolatey is installed from your internal repository
Environment chocoDownloadUrl {
Name = "chocolateyDownloadUrl"
Value = $ChocolateyNupkgUrl
}
cChocoInstaller installChocolatey {
DependsOn = "[Environment]chocoDownloadUrl"
InstallDir = Join-Path $env:ProgramData "chocolatey"
ChocoInstallScriptUrl = $ChocolateyInstallPs1Url
}
## 4. CONFIGURE CHOCOLATEY BASELINE ##
### a. FIPS Feature ###
#### If you need FIPS compliance - make this the first thing you configure
#### before you do any additional configuration or package installations
# cChocoFeature featureFipsCompliance {
# FeatureName = "useFipsCompliantChecksums"
# }
### b. Apply Recommended Configuration ###
#### Move cache location so Chocolatey is very deterministic about
#### cleaning up temporary data and the location is secured to admins
cChocoConfig cacheLocation {
DependsOn = "[cChocoInstaller]installChocolatey"
ConfigName = "cacheLocation"
Value = "C:\ProgramData\chocolatey\cache"
}
#### Increase timeout to at least 4 hours
cChocoConfig commandExecutionTimeoutSeconds {
DependsOn = "[cChocoInstaller]installChocolatey"
ConfigName = "commandExecutionTimeoutSeconds"
Value = 14400
}
#### Turn off download progress when running choco through integrations
cChocoFeature showDownloadProgress {
DependsOn = "[cChocoInstaller]installChocolatey"
FeatureName = "showDownloadProgress"
Ensure = "Absent"
}
### c. Sources ###
#### Remove the default community package repository source
cChocoSource removeCommunityRepository {
DependsOn = "[cChocoInstaller]installChocolatey"
Name = "chocolatey"
Ensure = "Absent"
}
#### Add internal default sources
#### You could have multiple sources here, so we will provide an example
#### of one using the remote repo variable here.
#### NOTE: This EXAMPLE may require changes
cChocoSource addInternalSource {
DependsOn = "[cChocoInstaller]installChocolatey"
Name = "ChocolateyInternal"
Source = $NugetRepositoryUrl
Credentials = $NugetRepositoryCredential
Priority = 1
}
### b. Keep Chocolatey Up To Date ###
#### Keep chocolatey up to date based on your internal source
#### You control the upgrades based on when you push an updated version
#### to your internal repository.
#### Note the source here is to the OData feed, similar to what you see
#### when you browse to https://community.chocolatey.org/api/v2/
cChocoPackageInstaller updateChocolatey {
DependsOn = "[cChocoSource]addInternalSource", "[cChocoSource]removeCommunityRepository"
Name = "chocolatey"
AutoUpgrade = $true
}
## 5. ENSURE CHOCOLATEY FOR BUSINESS ##
### If you don't have Chocolatey for Business (C4B), you'll want to remove from here down.
### a. Ensure The License File Is Installed ###
#### Create a license package using script from https://docs.chocolatey.org/en-us/how-tos/setup-offline-installation#exercise-4-create-a-package-for-the-license
cChocoPackageInstaller chocolateyLicense {
DependsOn = "[cChocoPackageInstaller]updateChocolatey"
Name = "chocolatey-license"
}
### b. Disable The Licensed Source ###
#### The licensed source cannot be removed, so it must be disabled.
#### This must occur after the license has been set by the license package.
Script disableLicensedSource {
DependsOn = "[cChocoPackageInstaller]chocolateyLicense"
GetScript = {
$Source = choco source list --limitoutput | `
ConvertFrom-Csv -Delimiter '|' -Header Name, Source, Disabled | `
Where-Object Name -eq "chocolatey.licensed"
return @{
Result = if ($Source) {
[bool]::Parse($Source.Disabled)
} else {
Write-Warning "Source 'chocolatey.licensed' was not present."
$true # Source does not need disabling
}
}
}
SetScript = {
$null = choco source disable --name "chocolatey.licensed"
}
TestScript = {
$State = [ScriptBlock]::Create($GetScript).Invoke()
return $State.Result
}
}
### c. Ensure Chocolatey Licensed Extension ###
#### You will have downloaded the licensed extension to your internal repository
#### as you have disabled the licensed repository in step 5b.
#### Ensure the chocolatey.extension package (aka Chocolatey Licensed Extension)
cChocoPackageInstaller chocolateyLicensedExtension {
DependsOn = "[Script]disableLicensedSource"
Name = "chocolatey.extension"
}
#### The Chocolatey Licensed Extension unlocks all of the following, which also have configuration/feature items available with them. You may want to visit the feature pages to see what you might want to also enable:
#### - Package Builder - https://docs.chocolatey.org/en-us/features/paid/package-builder
#### - Package Internalizer - https://docs.chocolatey.org/en-us/features/paid/package-internalizer
#### - Package Synchronization (3 components) - https://docs.chocolatey.org/en-us/features/paid/package-synchronization
#### - Package Reducer - https://docs.chocolatey.org/en-us/features/paid/package-reducer
#### - Package Audit - https://docs.chocolatey.org/en-us/features/paid/package-audit
#### - Package Throttle - https://docs.chocolatey.org/en-us/features/paid/package-throttle
#### - CDN Cache Access - https://docs.chocolatey.org/en-us/features/paid/private-cdn
#### - Branding - https://docs.chocolatey.org/en-us/features/paid/branding
#### - Self-Service Anywhere (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/self-service-anywhere
#### - Chocolatey Central Management (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/chocolatey-central-management
#### - Other - https://docs.chocolatey.org/en-us/features/paid/
### d. Ensure Self-Service Anywhere ###
#### If you have desktop clients where users are not administrators, you may
#### to take advantage of deploying and configuring Self-Service anywhere
cChocoFeature hideElevatedWarnings {
DependsOn = "[cChocoPackageInstaller]chocolateyLicensedExtension"
FeatureName = "showNonElevatedWarnings"
Ensure = "Absent"
}
cChocoFeature useBackgroundService {
DependsOn = "[cChocoPackageInstaller]chocolateyLicensedExtension"
FeatureName = "useBackgroundService"
Ensure = "Present"
}
cChocoFeature useBackgroundServiceWithNonAdmins {
DependsOn = "[cChocoPackageInstaller]chocolateyLicensedExtension"
FeatureName = "useBackgroundServiceWithNonAdministratorsOnly"
Ensure = "Present"
}
cChocoFeature useBackgroundServiceUninstallsForUserInstalls {
DependsOn = "[cChocoPackageInstaller]chocolateyLicensedExtension"
FeatureName = "allowBackgroundServiceUninstallsFromUserInstallsOnly"
Ensure = "Present"
}
cChocoConfig allowedBackgroundServiceCommands {
DependsOn = "[cChocoFeature]useBackgroundService"
ConfigName = "backgroundServiceAllowedCommands"
Value = "install,upgrade,uninstall"
}
### e. Ensure Chocolatey Central Management ###
#### If you want to manage and report on endpoints, you can set up and configure
### Central Management. There are multiple portions to manage, so you'll see
### a section on agents here along with notes on how to configure the server
### side components.
if ($ChocolateyCentralManagementUrl) {
cChocoPackageInstaller chocolateyAgent {
DependsOn = "[cChocoPackageInstaller]chocolateyLicensedExtension"
Name = "chocolatey-agent"
}
cChocoConfig centralManagementServiceUrl {
DependsOn = "[cChocoPackageInstaller]chocolateyAgent"
ConfigName = "CentralManagementServiceUrl"
Value = $ChocolateyCentralManagementUrl
}
if ($ChocolateyCentralManagementClientSalt) {
cChocoConfig centralManagementClientSalt {
DependsOn = "[cChocoPackageInstaller]chocolateyAgent"
ConfigName = "centralManagementClientCommunicationSaltAdditivePassword"
Value = $ChocolateyCentralManagementClientSalt
}
}
if ($ChocolateyCentralManagementServiceSalt) {
cChocoConfig centralManagementServiceSalt {
DependsOn = "[cChocoPackageInstaller]chocolateyAgent"
ConfigName = "centralManagementServiceCommunicationSaltAdditivePassword"
Value = $ChocolateyCentralManagementServiceSalt
}
}
cChocoFeature useCentralManagement {
DependsOn = "[cChocoPackageInstaller]chocolateyAgent"
FeatureName = "useChocolateyCentralManagement"
Ensure = "Present"
}
cChocoFeature useCentralManagementDeployments {
DependsOn = "[cChocoPackageInstaller]chocolateyAgent"
FeatureName = "useChocolateyCentralManagementDeployments"
Ensure = "Present"
}
}
}
}
# If working this into an existing configuration with a good method for
$ConfigData = @{
AllNodes = @(
@{
NodeName = "localhost"
PSDscAllowPlainTextPassword = $true
}
)
}
try {
Push-Location $env:Temp
$Config = ChocolateyConfig -ConfigurationData $ConfigData
Start-DscConfiguration -Path $Config.PSParentPath -Wait -Verbose -Force
} finally {
Pop-Location
}
Requires Puppet Chocolatey Provider module. See docs at https://forge.puppet.com/puppetlabs/chocolatey.
If Applicable - Chocolatey Configuration/Installation
## 1. REQUIREMENTS ##
### Here are the requirements necessary to ensure this is successful.
### a. Internal/Private Cloud Repository Set Up ###
#### You'll need an internal/private cloud repository you can use. These are
#### generally really quick to set up and there are quite a few options.
#### Chocolatey Software recommends Nexus, Artifactory Pro, or ProGet as they
#### are repository servers and will give you the ability to manage multiple
#### repositories and types from one server installation.
### b. Download Chocolatey Package and Put on Internal Repository ###
#### You need to have downloaded the Chocolatey package as well.
#### Please see https://chocolatey.org/install#organization
### c. Other Requirements ###
#### i. Requires puppetlabs/chocolatey module
#### See https://forge.puppet.com/puppetlabs/chocolatey
## 2. TOP LEVEL VARIABLES ##
### a. Your internal repository url (the main one). ###
#### Should be similar to what you see when you browse
#### to https://community.chocolatey.org/api/v2/
$_repository_url = 'INTERNAL REPO URL'
### b. Chocolatey nupkg download url ###
#### This url should result in an immediate download when you navigate to it in
#### a web browser
$_choco_download_url = 'INTERNAL REPO URL/package/chocolatey.1.1.0.nupkg'
### c. Chocolatey Central Management (CCM) ###
#### If using CCM to manage Chocolatey, add the following:
#### i. Endpoint URL for CCM
# $_chocolatey_central_management_url = 'https://chocolatey-central-management:24020/ChocolateyManagementService'
#### ii. If using a Client Salt, add it here
# $_chocolatey_central_management_client_salt = "clientsalt"
#### iii. If using a Service Salt, add it here
# $_chocolatey_central_management_service_salt = 'servicesalt'
## 3. ENSURE CHOCOLATEY IS INSTALLED ##
### Ensure Chocolatey is installed from your internal repository
### Note: `chocolatey_download_url is completely different than normal
### source locations. This is directly to the bare download url for the
### chocolatey.nupkg, similar to what you see when you browse to
### https://community.chocolatey.org/api/v2/package/chocolatey
class {'chocolatey':
chocolatey_download_url => $_choco_download_url,
use_7zip => false,
}
## 4. CONFIGURE CHOCOLATEY BASELINE ##
### a. FIPS Feature ###
#### If you need FIPS compliance - make this the first thing you configure
#### before you do any additional configuration or package installations
#chocolateyfeature {'useFipsCompliantChecksums':
# ensure => enabled,
#}
### b. Apply Recommended Configuration ###
#### Move cache location so Chocolatey is very deterministic about
#### cleaning up temporary data and the location is secured to admins
chocolateyconfig {'cacheLocation':
value => 'C:\ProgramData\chocolatey\cache',
}
#### Increase timeout to at least 4 hours
chocolateyconfig {'commandExecutionTimeoutSeconds':
value => '14400',
}
#### Turn off download progress when running choco through integrations
chocolateyfeature {'showDownloadProgress':
ensure => disabled,
}
### c. Sources ###
#### Remove the default community package repository source
chocolateysource {'chocolatey':
ensure => absent,
location => 'https://community.chocolatey.org/api/v2/',
}
#### Add internal default sources
#### You could have multiple sources here, so we will provide an example
#### of one using the remote repo variable here
#### NOTE: This EXAMPLE requires changes
chocolateysource {'internal_chocolatey':
ensure => present,
location => $_repository_url,
priority => 1,
username => 'optional',
password => 'optional,not ensured',
bypass_proxy => true,
admin_only => false,
allow_self_service => false,
}
### b. Keep Chocolatey Up To Date ###
#### Keep chocolatey up to date based on your internal source
#### You control the upgrades based on when you push an updated version
#### to your internal repository.
#### Note the source here is to the OData feed, similar to what you see
#### when you browse to https://community.chocolatey.org/api/v2/
package {'chocolatey':
ensure => latest,
provider => chocolatey,
source => $_repository_url,
}
## 5. ENSURE CHOCOLATEY FOR BUSINESS ##
### If you don't have Chocolatey for Business (C4B), you'll want to remove from here down.
### a. Ensure The License File Is Installed ###
#### Create a license package using script from https://docs.chocolatey.org/en-us/guides/organizations/organizational-deployment-guide#exercise-4-create-a-package-for-the-license
# TODO: Add resource for installing/ensuring the chocolatey-license package
package {'chocolatey-license':
ensure => latest,
provider => chocolatey,
source => $_repository_url,
}
### b. Disable The Licensed Source ###
#### The licensed source cannot be removed, so it must be disabled.
#### This must occur after the license has been set by the license package.
## Disabled sources still need all other attributes until
## https://tickets.puppetlabs.com/browse/MODULES-4449 is resolved.
## Password is necessary with user, but not ensurable, so it should not
## matter what it is set to here. If you ever do get into trouble here,
## the password is your license GUID.
chocolateysource {'chocolatey.licensed':
ensure => disabled,
priority => '10',
user => 'customer',
password => '1234',
require => Package['chocolatey-license'],
}
### c. Ensure Chocolatey Licensed Extension ###
#### You will have downloaded the licensed extension to your internal repository
#### as you have disabled the licensed repository in step 5b.
#### Ensure the chocolatey.extension package (aka Chocolatey Licensed Extension)
package {'chocolatey.extension':
ensure => latest,
provider => chocolatey,
source => $_repository_url,
require => Package['chocolatey-license'],
}
#### The Chocolatey Licensed Extension unlocks all of the following, which also have configuration/feature items available with them. You may want to visit the feature pages to see what you might want to also enable:
#### - Package Builder - https://docs.chocolatey.org/en-us/features/paid/package-builder
#### - Package Internalizer - https://docs.chocolatey.org/en-us/features/paid/package-internalizer
#### - Package Synchronization (3 components) - https://docs.chocolatey.org/en-us/features/paid/package-synchronization
#### - Package Reducer - https://docs.chocolatey.org/en-us/features/paid/package-reducer
#### - Package Audit - https://docs.chocolatey.org/en-us/features/paid/package-audit
#### - Package Throttle - https://docs.chocolatey.org/en-us/features/paid/package-throttle
#### - CDN Cache Access - https://docs.chocolatey.org/en-us/features/paid/private-cdn
#### - Branding - https://docs.chocolatey.org/en-us/features/paid/branding
#### - Self-Service Anywhere (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/self-service-anywhere
#### - Chocolatey Central Management (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/chocolatey-central-management
#### - Other - https://docs.chocolatey.org/en-us/features/paid/
### d. Ensure Self-Service Anywhere ###
#### If you have desktop clients where users are not administrators, you may
#### to take advantage of deploying and configuring Self-Service anywhere
chocolateyfeature {'showNonElevatedWarnings':
ensure => disabled,
}
chocolateyfeature {'useBackgroundService':
ensure => enabled,
}
chocolateyfeature {'useBackgroundServiceWithNonAdministratorsOnly':
ensure => enabled,
}
chocolateyfeature {'allowBackgroundServiceUninstallsFromUserInstallsOnly':
ensure => enabled,
}
chocolateyconfig {'backgroundServiceAllowedCommands':
value => 'install,upgrade,uninstall',
}
### e. Ensure Chocolatey Central Management ###
#### If you want to manage and report on endpoints, you can set up and configure
### Central Management. There are multiple portions to manage, so you'll see
### a section on agents here along with notes on how to configure the server
### side components.
if $_chocolatey_central_management_url {
package {'chocolatey-agent':
ensure => latest,
provider => chocolatey,
source => $_repository_url,
require => Package['chocolatey-license'],
}
chocolateyconfig {'CentralManagementServiceUrl':
value => $_chocolatey_central_management_url,
}
if $_chocolatey_central_management_client_salt {
chocolateyconfig {'centralManagementClientCommunicationSaltAdditivePassword':
value => $_chocolatey_central_management_client_salt,
}
}
if $_chocolatey_central_management_service_salt {
chocolateyconfig {'centralManagementClientCommunicationSaltAdditivePassword':
value => $_chocolatey_central_management_client_salt,
}
}
chocolateyfeature {'useChocolateyCentralManagement':
ensure => enabled,
require => Package['chocolatey-agent'],
}
chocolateyfeature {'useChocolateyCentralManagementDeployments':
ensure => enabled,
require => Package['chocolatey-agent'],
}
}
Need Help? View our docs or file an issue.
There is already a version of this package in your Script Builder
Current Version | New Version |
---|---|
- Passing
- Failing
- Pending
- Unknown / Exempted

Downloads:
9,959,266
Downloads of v 1.6.0-rc1:
333
Last Update:
11 Feb 2018
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
This is a prerelease version of Chocolatey Visual Studio servicing extensions.
- 1
- 2
- 3
1.6.0-rc1 | Updated: 11 Feb 2018
- 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:
9,959,266
Downloads of v 1.6.0-rc1:
333
Maintainer(s):
Software Author(s):
- Jakub Bereżański
Edit Package
To edit the metadata for a package, please upload an updated version of the package.
Chocolatey's Community Package Repository currently does not allow updating package metadata on the website. This helps ensure that the package itself (and the source used to build the package) remains the one true source of package metadata.
This does require that you increment the package version.
- 1
- 2
- 3
Chocolatey Visual Studio servicing extensions
1.6.0-rc1
This is a prerelease version of Chocolatey Visual Studio servicing extensions.
- 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:
📝 NOTE: This applies to both open source and commercial editions of Chocolatey.
1. Enter Your Internal Repository Url
(this should look similar to https://community.chocolatey.org/api/v2/)
2. Setup Your Environment
1. Ensure you are set for organizational deployment
Please see the organizational deployment guide
2. Get the package into your environment
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 --version=1.6.0-rc1 --pre --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'" --version="'1.6.0-rc1'" --prerelease [other options]
See options you can pass to upgrade.
See best practices for scripting.
Add this to a PowerShell script or use a Batch script with tools and in places where you are calling directly to Chocolatey. If you are integrating, keep in mind enhanced exit codes.
If you do use a PowerShell script, use the following to ensure bad exit codes are shown as failures:
choco upgrade chocolatey-visualstudio.extension -y --source="'INTERNAL REPO URL'" --version="'1.6.0-rc1'" --prerelease
$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.6.0-rc1'
source: INTERNAL REPO URL
state: present
allow_prerelease: yes
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.6.0-rc1'
options '--prerelease'
end
See docs at https://docs.chef.io/resource_chocolatey_package.html.
cChocoPackageInstaller chocolatey-visualstudio.extension
{
Name = "chocolatey-visualstudio.extension"
Version = "1.6.0-rc1"
Source = "INTERNAL REPO URL"
chocoParams = "--prerelease"
}
Requires cChoco DSC Resource. See docs at https://github.com/chocolatey/cChoco.
package { 'chocolatey-visualstudio.extension':
ensure => '1.6.0-rc1',
install_options => ['--prerelease'],
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 was approved as a trusted package on 11 Feb 2018.
This package provides helper functions useful for developing packages for installing and servicing Microsoft Visual Studio.
# CHANGELOG
## Version 1.6.0
- New helper: Install-VisualStudioVsixExtension. Supports Visual Studio 2010-2017 and replaces Install-ChocolateyVsixPackage.
## 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.
function Add-VisualStudioComponent
{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)] [string] $PackageName,
[Parameter(Mandatory = $true)] [string] $Component,
[Parameter(Mandatory = $true)] [string] $VisualStudioYear,
[Parameter(Mandatory = $true)] [string[]] $ApplicableProducts
)
if ($Env:ChocolateyPackageDebug -ne $null)
{
$VerbosePreference = 'Continue'
$DebugPreference = 'Continue'
Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
}
Write-Debug "Running 'Add-VisualStudioComponent' with PackageName:'$PackageName' Component:'$Component' VisualStudioYear:'$VisualStudioYear'";
$argumentList = @('add', "$Component")
Start-VisualStudioModifyOperation -PackageName $PackageName -ArgumentList $argumentList -VisualStudioYear $VisualStudioYear -ApplicableProducts $ApplicableProducts -OperationTexts @('installed', 'installing', 'installation')
}
function Add-VisualStudioWorkload
{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)] [string] $PackageName,
[Parameter(Mandatory = $true)] [string] $Workload,
[Parameter(Mandatory = $true)] [string] $VisualStudioYear,
[Parameter(Mandatory = $true)] [string[]] $ApplicableProducts,
[switch] $IncludeRecommendedComponentsByDefault
)
if ($Env:ChocolateyPackageDebug -ne $null)
{
$VerbosePreference = 'Continue'
$DebugPreference = 'Continue'
Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
}
Write-Debug "Running 'Add-VisualStudioWorkload' with PackageName:'$PackageName' Workload:'$Workload' VisualStudioYear:'$VisualStudioYear' IncludeRecommendedComponentsByDefault:'$IncludeRecommendedComponentsByDefault'";
$argumentList = @('add', "Microsoft.VisualStudio.Workload.$Workload")
if ($IncludeRecommendedComponentsByDefault)
{
$argumentList += @('includeRecommended', '')
}
Start-VisualStudioModifyOperation -PackageName $PackageName -ArgumentList $argumentList -VisualStudioYear $VisualStudioYear -ApplicableProducts $ApplicableProducts -OperationTexts @('installed', 'installing', 'installation')
}
Set-StrictMode -Version 2
$ErrorActionPreference = 'Stop'
$scriptRoot = Split-Path -Path $MyInvocation.MyCommand.Definition
$publicFunctions = @(
'Install-VisualStudio'
'Uninstall-VisualStudio'
'Add-VisualStudioWorkload'
'Add-VisualStudioComponent'
'Remove-VisualStudioWorkload'
'Remove-VisualStudioComponent'
'Remove-VisualStudioProduct'
'Get-VisualStudioInstance'
'Get-VisualStudioInstaller'
'Install-VisualStudioInstaller'
'Install-VisualStudioVsixExtension'
)
Get-ChildItem -Path "$scriptRoot\*.ps1" | ForEach-Object { . $_ }
Export-ModuleMember -Function $publicFunctions
# Generates customizations file. Returns its path
function Generate-AdminFile
{
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[hashtable] $parameters,
[string] $adminFile,
[Parameter(Mandatory = $true)]
[string] $packageName
)
Write-Debug "Running 'Generate-AdminFile' with parameters:'$parameters', defaultAdminFile:'$defaultAdminFile', packageName:'$packageName'";
$adminFile = $parameters['AdminFile']
$features = $parameters['Features']
if ($adminFile -eq '' -and !$features)
{
return $null
}
$localAdminFile = Join-Path $Env:TEMP "${packageName}_AdminDeployment.xml"
if (Test-Path $localAdminFile)
{
Remove-Item $localAdminFile
}
if ($adminFile)
{
if (Test-Path $adminFile)
{
Copy-Item $adminFile $localAdminFile -force
}
else
{
if (($adminFile -as [System.URI]).AbsoluteURI -ne $null)
{
Get-ChocolateyWebFile 'adminFile' $localAdminFile $adminFile
}
else
{
throw 'Invalid AdminFile setting.'
}
}
Write-Verbose "Using provided AdminFile: $adminFile"
}
elseif ($features)
{
Copy-Item $defaultAdminFile $localAdminFile -force
}
return $localAdminFile
}
function Generate-InstallArgumentsString
{
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[hashtable] $parameters,
[string] $adminFile,
[string] $logFilePath,
[switch] $assumeNewVS2017Installer
)
Write-Debug "Running 'Generate-InstallArgumentsString' with parameters:'$parameters', adminFile:'$adminFile', logFilePath:'$logFilePath', assumeNewVS2017Installer:'$assumeNewVS2017Installer'";
if ($assumeNewVS2017Installer)
{
if ($logFilePath -ne '')
{
Write-Warning "The new VS 2017 installer does not support setting the path to the log file yet."
}
if ($adminFile -ne '')
{
Write-Warning "The new VS 2017 installer does not support an admin file yet."
}
$argumentSet = $parameters.Clone()
$argumentSet['wait'] = ''
if (-not $argumentSet.ContainsKey('layout'))
{
$argumentSet['norestart'] = ''
}
if (-not $argumentSet.ContainsKey('quiet') -and -not $argumentSet.ContainsKey('passive'))
{
$argumentSet['quiet'] = ''
}
$s = ($argumentSet.GetEnumerator() | ForEach-Object { '--{0} {1}' -f $_.Key, $_.Value }) -f ' '
}
else
{
$s = "/Quiet /NoRestart"
if ($logFilePath -ne '')
{
$s = $s + " /Log ""$logFilePath"""
}
if ($adminFile -ne '')
{
$s = $s + " /AdminFile $adminFile"
}
if ($parameters.ContainsKey('layout'))
{
# TODO: CHECK THIS, perhaps /NoRestart is incompatible with this?
$s = $s + " /Layout ""$($parameters['layout'])"""
}
}
$pk = $parameters['ProductKey']
if ($pk -and (-not [string]::IsNullOrEmpty($pk)))
{
Write-Verbose "Using provided product key: ...-$($pk.Substring([Math]::Max($pk.Length - 5, 0)))"
if ($assumeNewVS2017Installer)
{
# nothing to do, all package parameters are passed to Willow
}
else
{
$s = $s + " /ProductKey $pk"
}
}
return $s
}
function Generate-UninstallArgumentsString
{
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[hashtable] $parameters,
[string] $logFilePath,
[switch] $assumeNewVS2017Installer
)
Write-Debug "Running 'Generate-UninstallArgumentsString' with logFilePath:'$logFilePath', assumeNewVS2017Installer:'$assumeNewVS2017Installer'";
if ($assumeNewVS2017Installer)
{
if ($logFilePath -ne '')
{
Write-Warning "The new VS 2017 installer does not support setting the path to the log file yet."
}
$argumentSet = $parameters.Clone()
$argumentSet['norestart'] = ''
if (-not $argumentSet.ContainsKey('quiet') -and -not $argumentSet.ContainsKey('passive'))
{
$argumentSet['quiet'] = ''
}
$s = '/uninstall ' + (($argumentSet.GetEnumerator() | ForEach-Object { '--{0} {1}' -f $_.Key, $_.Value }) -f ' ')
}
else
{
$s = "/Uninstall /Force /Quiet /NoRestart"
if ($logFilePath -ne '')
{
$s = $s + " /Log ""$logFilePath"""
}
}
return $s
}
function Get-VisualStudioInstaller
{
<#
.SYNOPSIS
Returns information about the Visual Studio 2017 Installer.
.DESCRIPTION
This function returns an object containing the basic properties (path, version)
of the Visual Studio Installer used by VS 2017 (vs_installer.exe),
if it is present.
.OUTPUTS
A System.Management.Automation.PSObject with the following properties:
Path (System.String)
Version (System.Version)
#>
[CmdletBinding()]
Param
(
)
$rxVersion = [regex]'"version":\s+"(?<value>[0-9\.]+)"'
$basePaths = @(${Env:ProgramFiles}, ${Env:ProgramFiles(x86)}, ${Env:ProgramW6432})
$installer = $basePaths | Where-Object { $_ -ne $null } | Sort-Object -Unique | ForEach-Object {
$candidate = Join-Path -Path $_ -ChildPath 'Microsoft Visual Studio\Installer\vs_installer.exe'
if (Test-Path -Path $candidate)
{
Write-Debug "Located VS installer executable: $candidate"
$version = $null
$versionJsonPath = Join-Path -Path (Split-Path -Parent -Path $candidate) -ChildPath 'vs_installer.version.json'
if (Test-Path -Path $versionJsonPath)
{
$text = Get-Content -Path $versionJsonPath
$matches = $rxVersion.Matches($text)
foreach ($match in $matches)
{
if ($match -eq $null -or -not $match.Success)
{
continue
}
$value = $match.Groups['value'].Value
try
{
$version = [version]$value
}
catch
{
Write-Warning ('Unable to parse Visual Studio Installer version ''{0}'' ({1})' -f $value, $_)
}
}
}
else
{
Write-Warning ('Visual Studio Installer version file not found: {0}' -f $versionJsonPath)
}
$item = Get-Item -Path $candidate
$props = @{
Path = $candidate
Version = $version
}
$obj = New-Object -TypeName PSObject -Property $props
Write-Verbose ('Visual Studio Installer version {0} is present ({1}).' -f $obj.Version, $obj.Path)
Write-Output $obj
}
}
$installerCount = ($installer | Measure-Object).Count
if ($installerCount -eq 0)
{
Write-Verbose 'Visual Studio Installer is not present.'
}
elseif ($installerCount -gt 1)
{
Write-Warning ('Multiple instances of Visual Studio Installer found ({0}), using the first one. This is unexpected, please inform the maintainer of this package.' -f $installerCount)
}
$installer | Select-Object -First 1 | Write-Output
}
function Get-VisualStudioInstance
{
<#
.SYNOPSIS
Returns information about installed Visual Studio instances.
.DESCRIPTION
For each Visual Studio instance installed on the machine, this function returns an object
containing the basic properties of the instance.
.OUTPUTS
A System.Management.Automation.PSObject with the following properties:
InstallationPath (System.String)
InstallationVersion (System.Version)
ProductId (System.String; Visual Studio 2017 only)
ChannelId (System.String; Visual Studio 2017 only)
#>
[CmdletBinding()]
Param
(
)
Get-WillowInstalledProducts | Where-Object { $_ -ne $null } | ForEach-Object {
$props = @{
InstallationPath = $_.installationPath
InstallationVersion = [version]$_.installationVersion
ProductId = $_.productId
ChannelId = $_.channelId
}
$obj = New-Object -TypeName PSObject -Property $props
Write-Output $obj
}
Get-VSLegacyInstance | Where-Object { $_ -ne $null } | ForEach-Object {
$props = @{
InstallationPath = $_.Path
InstallationVersion = $_.Version
ProductId = $null
ChannelId = $null
}
$obj = New-Object -TypeName PSObject -Property $props
Write-Output $obj
}
}
function Get-VsixInstaller
{
[CmdletBinding()]
Param
(
[switch] $Latest
)
Write-Debug "Running 'Get-VsixInstaller' with Latest:'$Latest'";
$candidates = New-Object System.Collections.ArrayList
$modernProducts = Get-WillowInstalledProducts
$modernProducts `
| Where-Object { $_ -ne $null } `
| ForEach-Object { $_['enginePath'] } `
| Where-Object { -not [string]::IsNullOrEmpty($_) } `
| Select-Object -Unique `
| ForEach-Object { Get-Item -Path "$_\VSIXInstaller.exe" -ErrorAction SilentlyContinue } `
| ForEach-Object { [void]$candidates.Add($_) }
if (-not $Latest -or $candidates.Count -eq 0)
{
$legacyProducts = Get-VSLegacyInstance
$legacyProducts `
| Where-Object { $_ -ne $null } `
| Select-Object -ExpandProperty Path -Unique `
| Where-Object { -not [string]::IsNullOrEmpty($_) } `
| ForEach-Object { Get-Item -Path "$_\Common7\IDE\VSIXInstaller.exe" -ErrorAction SilentlyContinue } `
| ForEach-Object { [void]$candidates.Add($_) }
}
else
{
Write-Debug 'Not looking for VSIXInstaller in legacy VS products because -Latest was specified and more modern VS product(s) were found.'
}
$rxVersion = [regex]'^\d+(\.\d+)+'
$sortedCandidates = $candidates `
| Select-Object -Property `
@{ Name = 'Path'; Expression = { $_.FullName } },
@{ Name = 'Version'; Expression = { [version]($rxVersion.Match($_.VersionInfo.ProductVersion).Value) } } `
| Sort-Object -Property Version -Descending `
| ForEach-Object { Write-Debug ('Found VSIXInstaller.exe version ''{0}'': {1}' -f $_.Version, $_.Path); $_ }
if ($Latest)
{
if (($sortedCandidates | Measure-Object).Count -eq 0)
{
Write-Error 'The VSIX Installer is not present.'
}
else
{
Write-Output ($sortedCandidates[0])
}
}
else
{
$sortedCandidates | Write-Output
}
}
function Get-VSLegacyInstance
{
[CmdletBinding()]
Param
(
)
Write-Debug 'Detecting Visual Studio products installed using the classic MSI installer (2015 and earlier)'
$bitness = [IntPtr]::Size * 8
if ($bitness -eq 64)
{
$basePath = 'HKLM:\SOFTWARE\WOW6432Node'
}
else
{
$basePath = 'HKLM:\SOFTWARE'
}
Write-Debug "Process bitness is $bitness, using '$basePath' as base registry path"
$keyPath = Join-Path -Path $basePath -ChildPath 'Microsoft\VisualStudio\SxS\VS7'
$classicInstanceCount = 0
if (-not (Test-Path -Path $keyPath))
{
Write-Debug "VS registry key '$keyPath' does not exist."
}
else
{
Write-Debug "Enumerating properties of key '$keyPath'"
$props = Get-ItemProperty -Path $keyPath
$props.PSObject.Properties | Where-Object { $_.Name -match '^\d+\.\d+$' } | ForEach-Object {
$prop = $_
Write-Debug ('Found possible classic VS instance: ''{0}'' = ''{1}''' -f $prop.Name, $prop.Value)
$version = [version]$prop.Name
if ($version -ge [version]'15.0')
{
Write-Debug ('VS instance version is 15.0 or greater, skipping (not a classic instance)')
}
else
{
$path = $prop.Value
Write-Verbose ('Found classic VS instance: {0} = ''{1}''' -f $version, $path)
$instanceProps = @{
Version = $version
Path = $path
}
$instance = New-Object -TypeName PSObject -Property $instanceProps
Write-Output $instance
$classicInstanceCount += 1
}
}
}
if ($classicInstanceCount -eq 0)
{
Write-Verbose 'No classic (MSI) Visual Studio installations detected.'
}
else
{
Write-Verbose "Detected $classicInstanceCount classic (MSI) Visual Studio installations."
}
}
function Get-VSProductReference
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)] [string] $VisualStudioYear,
[Parameter(Mandatory = $true)] [string] $Product
)
switch ($VisualStudioYear)
{
'2017' { $channelId = 'VisualStudio.15.Release' }
default { throw "Unsupported VisualStudioYear: $VisualStudioYear"}
}
$productId = "Microsoft.VisualStudio.Product." + $Product
$props = @{
ChannelId = $channelId
ProductId = $productId
}
$obj = New-Object -TypeName PSObject -Property $props
return $obj
}
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
)
Write-Debug "Running 'Get-VSWebFile' for $PackageName with Url:'$Url', Url64Bit:'$Url64Bit', Checksum:'$Checksum', ChecksumType:'$ChecksumType', Checksum64:'$Checksum64', ChecksumType64:'$ChecksumType64', LocalFilePath:'$LocalFilePath'";
if ($LocalFilePath -eq '') {
$chocTempDir = $env:TEMP
$tempDir = Join-Path $chocTempDir "$PackageName"
if ($env:packageVersion -ne $null) { $tempDir = Join-Path $tempDir "$env:packageVersion" }
if (![System.IO.Directory]::Exists($tempDir)) { [System.IO.Directory]::CreateDirectory($tempDir) | Out-Null }
$urlForFileNameDetermination = $Url
if ($urlForFileNameDetermination -eq '') { $urlForFileNameDetermination = $Url64Bit }
if ($urlForFileNameDetermination -match '\.((exe)|(vsix))$') { $localFileName = $urlForFileNameDetermination.Substring($urlForFileNameDetermination.LastIndexOfAny(@('/', '\')) + 1) }
else { $localFileName = $DefaultFileName }
$LocalFilePath = Join-Path $tempDir $localFileName
Write-Verbose "Downloading the $FileDescription"
$arguments = @{
PackageName = $PackageName
FileFullPath = $LocalFilePath
Url = $Url
Url64Bit = $Url64Bit
Checksum = $Checksum
ChecksumType = $ChecksumType
Checksum64 = $Checksum64
ChecksumType64 = $ChecksumType64
}
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] $VisualStudioYear,
[Parameter(Mandatory = $false)] [string] $BasePath = "$Env:ProgramData\Microsoft\VisualStudio\Packages\_Instances"
)
Write-Debug 'Detecting Visual Studio products installed using the Willow installer (2017+)'
if (-not (Test-Path -Path $BasePath))
{
Write-Debug "Base path '$BasePath' does not exist, assuming no products installed"
return $null
}
$expectedProductProperties = @{
productLineVersion = 'productLineVersion'
installationPath = 'installationPath'
installationVersion = 'installationVersion'
channelId = 'channelId'
productId = 'product"\s*:\s*{\s*"id'
enginePath = 'enginePath'
}
$optionalProductProperties = @{
nickname = 'nickname'
}
$propertyNameSelector = (($expectedProductProperties.Values + $optionalProductProperties.Values) | ForEach-Object { "($_)" }) -join '|'
$regexTextBasicInfo = '"(?<name>{0})"\s*:\s*"(?<value>[^\"]+)"' -f $propertyNameSelector
$rxBasicInfo = New-Object -TypeName System.Text.RegularExpressions.Regex -ArgumentList @($regexTextBasicInfo, 'ExplicitCapture,IgnorePatternWhitespace,Singleline')
$regexTextSingleProductInfo = '\s*{\s*[^}]*"id"\s*:\s*"(?<packageId>[^\"]+)"[^}]*}'
$rxSelectedPackages = [regex]('"selectedPackages"\s*:\s*\[(({0})(\s*,{0})*)\]' -f $regexTextSingleProductInfo)
$instanceDataPaths = Get-ChildItem -Path $BasePath | Where-Object { $_.PSIsContainer -eq $true } | Select-Object -ExpandProperty FullName
foreach ($instanceDataPath in $instanceDataPaths)
{
if ($instanceDataPath -eq $null)
{
continue
}
Write-Debug "Examining possible product instance: $instanceDataPath"
$stateJsonPath = Join-Path -Path $instanceDataPath -ChildPath 'state.json'
if (-not (Test-Path -Path $stateJsonPath))
{
Write-Warning "File state.json does not exist, this is not a Visual Studio product instance or the file layout has changed! (path: '$instanceDataPath')"
continue
}
$instanceData = @{ selectedPackages = @{} }
foreach ($name in ($expectedProductProperties.Keys + $optionalProductProperties.Keys))
{
$instanceData[$name] = $null
}
# unfortunately, PowerShell 2.0 does not have ConvertFrom-Json
$text = [IO.File]::ReadAllText($stateJsonPath)
$matches = $rxBasicInfo.Matches($text)
foreach ($match in $matches)
{
if ($match -eq $null -or -not $match.Success)
{
continue
}
$name = $match.Groups['name'].Value -replace '"id', 'Id' -replace '[^a-zA-Z]', ''
$value = $match.Groups['value'].Value -replace '\\\\', '\'
$instanceData[$name] = $value
}
Write-Debug ('Parsed instance data: {0}' -f (($instanceData.GetEnumerator() | ForEach-Object { '{0} = ''{1}''' -f $_.Key, $_.Value }) -join ' '))
$missingExpectedProperties = $expectedProductProperties.GetEnumerator() | Where-Object { -not $instanceData.ContainsKey($_.Key) } | Select-Object -ExpandProperty Key
if (($missingExpectedProperties | Measure-Object).Count -gt 0)
{
Write-Warning "Failed to fully parse state.json, perhaps the file structure has changed! (path: '$stateJsonPath' missing properties: $missingExpectedProperties)"
continue
}
if ($VisualStudioYear -ne '' -and $instanceData.productLineVersion -ne $VisualStudioYear)
{
Write-Debug "Skipping product because its productLineVersion ($($instanceData.productLineVersion)) is not equal to VisualStudioYear argument value ($VisualStudioYear)"
continue
}
$match = $rxSelectedPackages.Match($text)
if ($match.Success)
{
foreach ($capture in $match.Groups['packageId'].Captures)
{
$packageId = $capture.Value
$instanceData.selectedPackages[$packageId] = $true
}
}
Write-Debug ('Parsed instance selected packages: {0}' -f ($instanceData.selectedPackages.Keys -join ' '))
Write-Output $instanceData
}
}
function Install-VisualStudio {
<#
.SYNOPSIS
Installs Visual Studio
.DESCRIPTION
Installs Visual Studio with ability to specify additional features and supply product key.
.PARAMETER PackageName
The name of the VisualStudio package - this is arbitrary.
It's recommended you call it the same as your nuget package id.
.PARAMETER Url
This is the url to download the VS web installer.
.PARAMETER ChecksumSha1
The SHA-1 hash of the VS web installer file.
.EXAMPLE
Install-VisualStudio -PackageName VisualStudio2015Community -Url 'http://download.microsoft.com/download/zzz/vs_community.exe' -ChecksumSha1 'ABCDEF0123456789ABCDEF0123456789ABCDEF12'
.OUTPUTS
None
.NOTES
This helper reduces the number of lines one would have to write to download and install Visual Studio.
This method has no error handling built into it.
.LINK
Install-ChocolateyPackage
#>
[CmdletBinding()]
param(
[string] $PackageName,
[string] $ApplicationName,
[string] $Url,
[string] $Checksum,
[string] $ChecksumType,
[ValidateSet('MsiVS2015OrEarlier', 'WillowVS2017OrLater')] [string] $InstallerTechnology,
[string] $ProgramsAndFeaturesDisplayName = $ApplicationName,
[string] $VisualStudioYear,
[string] $Product
)
if ($Env:ChocolateyPackageDebug -ne $null)
{
$VerbosePreference = 'Continue'
$DebugPreference = 'Continue'
Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
}
Write-Debug "Running 'Install-VisualStudio' for $PackageName with ApplicationName:'$ApplicationName' Url:'$Url' Checksum:$Checksum ChecksumType:$ChecksumType InstallerTechnology:'$InstallerTechnology' ProgramsAndFeaturesDisplayName:'$ProgramsAndFeaturesDisplayName' VisualStudioYear:'$VisualStudioYear' Product:'$Product'";
$packageParameters = Parse-Parameters $env:chocolateyPackageParameters
$creatingLayout = $packageParameters.ContainsKey('layout')
$assumeNewVS2017Installer = $InstallerTechnology -eq 'WillowVS2017OrLater'
if (-not $creatingLayout)
{
if ($assumeNewVS2017Installer)
{
# there is a single Programs and Features entry for all products, so its presence is not enough
if ($VisualStudioYear -ne '' -and $Product -ne '')
{
$prodRef = Get-VSProductReference -VisualStudioYear $VisualStudioYear -Product $Product
$products = Get-WillowInstalledProducts | Where-Object { $_ -ne $null -and $_.channelId -eq $prodRef.ChannelId -and $_.productId -eq $prodRef.ProductId }
$productsCount = ($products | Measure-Object).Count
Write-Verbose ("Found {0} installed Visual Studio product(s) with ChannelId = {1} and ProductId = {2}" -f $productsCount, $prodRef.ChannelId, $prodRef.ProductId)
if ($productsCount -gt 0)
{
Write-Warning "$ApplicationName is already installed. Please use the Visual Studio Installer to modify or repair it."
return
}
}
}
else
{
$uninstallKey = Get-VSUninstallRegistryKey -ApplicationName $ProgramsAndFeaturesDisplayName
$count = ($uninstallKey | Measure-Object).Count
if ($count -gt 0)
{
Write-Warning "$ApplicationName is already installed. Please use Programs and Features in the Control Panel to modify or repair it."
return
}
}
}
if ($assumeNewVS2017Installer)
{
$adminFile = $null
$logFilePath = $null
}
else
{
$defaultAdminFile = (Join-Path $PSScriptRoot 'AdminDeployment.xml')
Write-Debug "Default AdminFile: $defaultAdminFile"
$adminFile = Generate-AdminFile $packageParameters $defaultAdminFile $PackageName
Write-Debug "AdminFile: $adminFile"
Update-AdminFile $packageParameters $adminFile
$logFilePath = Join-Path $Env:TEMP "${PackageName}.log"
Write-Debug "Log file path: $logFilePath"
}
if ($packageParameters.ContainsKey('bootstrapperPath'))
{
$installerFilePath = $packageParameters['bootstrapperPath']
$packageParameters.Remove('bootstrapperPath')
Write-Debug "User-provided bootstrapper path: $installerFilePath"
}
else
{
$installerFilePath = $null
}
$silentArgs = Generate-InstallArgumentsString -parameters $packageParameters -adminFile $adminFile -logFilePath $logFilePath -assumeNewVS2017Installer:$assumeNewVS2017Installer
if ($creatingLayout)
{
$layoutPath = $packageParameters['layout']
Write-Warning "Creating an offline installation source for $PackageName in '$layoutPath'. $PackageName will not be actually installed."
}
$arguments = @{
packageName = $PackageName
silentArgs = $silentArgs
url = $Url
checksum = $Checksum
checksumType = $ChecksumType
logFilePath = $logFilePath
assumeNewVS2017Installer = $assumeNewVS2017Installer
installerFilePath = $installerFilePath
}
$argumentsDump = ($arguments.GetEnumerator() | ForEach-Object { '-{0}:''{1}''' -f $_.Key,"$($_.Value)" }) -join ' '
Write-Debug "Install-VSChocolateyPackage $argumentsDump"
Install-VSChocolateyPackage @arguments
if ($creatingLayout)
{
Write-Warning "An offline installation source for $PackageName has been created in '$layoutPath'."
$bootstrapperExeName = $Url -split '[/\\]' | Select-Object -Last 1
if ($bootstrapperExeName -like '*.exe')
{
Write-Warning "To install $PackageName using this source, pass '--bootstrapperPath $layoutPath\$bootstrapperExeName' as package parameters."
}
Write-Warning 'Installation will now be terminated so that Chocolatey does not register this package as installed, do not be alarmed.'
Set-PowerShellExitCode -exitCode 814
throw 'An offline installation source has been created; the software has not been actually installed.'
}
}
function Install-VisualStudioInstaller
{
<#
.SYNOPSIS
Installs or updates the Visual Studio 2017 Installer.
.DESCRIPTION
This function checks for the presence of the Visual Studio 2017 Installer.
If the Installer is not present, it is installed using the bootstrapper application
(e.g. vs_FeedbackClient.exe), either downloaded from the provided $Url or indicated
via the 'bootstrapperPath' package parameter (which takes precedence).
If the Installer is present, it will be updated/reinstalled if:
- $RequiredVersion was provided and the existing Installer version is lower,
- $RequiredVersion was provided, the existing Installer version is equal and $Force
was specified,
- $RequiredVersion was not provided and $Force was specified.
#>
[CmdletBinding()]
param(
[string] $PackageName,
[string] $Url,
[string] $Checksum,
[string] $ChecksumType,
[version] $RequiredVersion,
[switch] $Force
)
if ($Env:ChocolateyPackageDebug -ne $null)
{
$VerbosePreference = 'Continue'
$DebugPreference = 'Continue'
Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
}
Write-Debug "Running 'Install-VisualStudioInstaller' for $PackageName with Url:'$Url' Checksum:$Checksum ChecksumType:$ChecksumType RequiredVersion:'$RequiredVersion' Force:'$Force'";
$existing = Get-VisualStudioInstaller
if ($existing -ne $null)
{
Write-Debug 'The Visual Studio Installer is already present'
if ($existing.Version -ne $null -and $RequiredVersion -ne $null)
{
if ($existing.Version -lt $RequiredVersion)
{
Write-Debug 'The existing Visual Studio Installer version is lower than requested, so it will be updated'
$shouldUpdate = $true
}
elseif ($existing.Version -eq $RequiredVersion)
{
if ($Force)
{
Write-Debug 'The existing Visual Studio Installer version is equal to requested, but it will be updated because -Force was used'
$shouldUpdate = $true
}
else
{
Write-Debug 'The existing Visual Studio Installer version is equal to requested, so it will not be updated'
$shouldUpdate = $false
}
}
else
{
Write-Debug 'The existing Visual Studio Installer version is greater than requested, so it will not be updated'
$shouldUpdate = $false
}
}
else
{
if ($Force)
{
Write-Debug 'The Visual Studio Installer is already present, but it will be updated because -Force was used'
$shouldUpdate = $true
}
else
{
Write-Debug 'The Visual Studio Installer is already present and will not be updated'
$shouldUpdate = $false
}
}
}
else
{
Write-Debug 'The Visual Studio Installer is not present and will be installed'
$shouldUpdate = $true
}
if (-not $shouldUpdate)
{
return
}
$packageParameters = Parse-Parameters $env:chocolateyPackageParameters
if ($packageParameters.ContainsKey('bootstrapperPath'))
{
$installerFilePath = $packageParameters['bootstrapperPath']
$packageParameters.Remove('bootstrapperPath')
Write-Debug "User-provided bootstrapper path: $installerFilePath"
}
else
{
$installerFilePath = $null
}
$silentArgsFromParameters = ($packageParameters.GetEnumerator() | ForEach-Object { '--{0} {1}' -f $_.Key, $_.Value }) -f ' '
# --update must be last
$silentArgs = "--quiet $silentArgsFromParameters --update"
$arguments = @{
packageName = $PackageName
silentArgs = $silentArgs
url = $Url
checksum = $Checksum
checksumType = $ChecksumType
logFilePath = $null
assumeNewVS2017Installer = $true
installerFilePath = $installerFilePath
}
$argumentsDump = ($arguments.GetEnumerator() | ForEach-Object { '-{0}:''{1}''' -f $_.Key,"$($_.Value)" }) -join ' '
Write-Debug "Install-VSChocolateyPackage $argumentsDump"
Install-VSChocolateyPackage @arguments
}
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.
#>
[CmdletBinding()]
Param
(
[Alias('Name')] [string] $PackageName,
[Alias('Url')] [string] $VsixUrl,
[string] $Checksum,
[string] $ChecksumType,
[Alias('VisualStudioVersion')] [int] $VsVersion,
[hashtable] $Options,
[string] $File
)
if ($Env:ChocolateyPackageDebug -ne $null)
{
$VerbosePreference = 'Continue'
$DebugPreference = 'Continue'
Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
}
Write-Debug "Running 'Install-VisualStudioVsixExtension' for $PackageName with VsixUrl:'$VsixUrl' Checksum:$Checksum ChecksumType:$ChecksumType VsVersion:$VsVersion Options:$Options File:$File";
if ($VsVersion -ne 0)
{
Write-Warning "VsVersion is not supported yet. The extension will be installed in all compatible Visual Studio instances present."
}
if ($Options -ne $null -and $Options.Keys.Count -gt 0)
{
Write-Warning "The 'Options' parameter is not supported yet."
}
if ($VsixUrl -eq '')
{
$VsixUrl = $File
}
$vsixInstaller = Get-VsixInstaller -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
Write-Host ('Installing {0} using VSIXInstaller version {1}' -f $PackageName, $vsixInstaller.Version)
$logFileName = 'VSIXInstaller_{0}_{1:yyyyMMddHHmmss}.log' -f $PackageName, (Get-Date)
$silentArgs = "/quiet /admin /logFile:$logFileName ""$vsixPath"""
$validExitCodes = @(0, 1001)
$exitCode = Start-VSChocolateyProcessAsAdmin -statements $silentArgs -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-ChocolateyInstallPackage (fbe24a8), with changes:
# - added recognition of exit codes signifying reboot requirement
# - VS installers are exe
# - dropped support for chocolateyInstallArguments and chocolateyInstallOverride
# - removed unreferenced parameter
# - refactored logic shared with Uninstall-VSChocolateyPackage to a generic function
# - removed exit code parameters in order to centralize exit code logic
function Install-VSChocolateyInstallPackage {
[CmdletBinding()]
param(
[string] $packageName,
[string] $silentArgs = '',
[string] $file,
[string] $logFilePath,
[switch] $assumeNewVS2017Installer
)
Write-Debug "Running 'Install-VSChocolateyInstallPackage' for $packageName with file:'$file', silentArgs:'$silentArgs', logFilePath:'$logFilePath', assumeNewVS2017Installer:'$assumeNewVS2017Installer'"
$installMessage = "Installing $packageName..."
Write-Host $installMessage
if ($file -eq '' -or $file -eq $null) {
throw 'Package parameters incorrect, File cannot be empty.'
}
Start-VSServicingOperation @PSBoundParameters -operationTexts @('installed', 'installing', 'installation')
}
# 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
}
# Parse input argument string into a hashtable
# Format: --AdminFile file location --Features WebTools,Win8SDK --ProductKey AB-D1
function Parse-Parameters
{
[CmdletBinding()]
Param (
[string] $s
)
Write-Debug "Running 'Parse-Parameters' with s:'$s'";
$parameters = @{ }
if ($s -eq '')
{
Write-Debug "No package parameters."
return $parameters
}
Write-Debug "Package parameters: $s"
$s = ' ' + $s
[String[]] $kvpPrefix = @(" --")
$kvpDelimiter = ' '
$kvps = $s.Split($kvpPrefix, [System.StringSplitOptions]::RemoveEmptyEntries)
foreach ($kvp in $kvps)
{
Write-Debug "Package parameter kvp: $kvp"
$delimiterIndex = $kvp.IndexOf($kvpDelimiter)
if (($delimiterIndex -le 0) -or ($delimiterIndex -ge ($kvp.Length - 1))) { $delimiterIndex = $kvp.Length }
$key = $kvp.Substring(0, $delimiterIndex).Trim()
if ($key -eq '') { continue }
if ($delimiterIndex -lt $kvp.Length)
{
$value = $kvp.Substring($delimiterIndex + 1).Trim()
}
else
{
$value = ''
}
Write-Debug "Package parameter: key=$key, value=$value"
$parameters.Add($key, $value)
}
return $parameters
}
function Remove-VisualStudioComponent
{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)] [string] $PackageName,
[Parameter(Mandatory = $true)] [string] $Component,
[Parameter(Mandatory = $true)] [string] $VisualStudioYear,
[Parameter(Mandatory = $true)] [string[]] $ApplicableProducts
)
if ($Env:ChocolateyPackageDebug -ne $null)
{
$VerbosePreference = 'Continue'
$DebugPreference = 'Continue'
Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
}
Write-Debug "Running 'Remove-VisualStudioComponent' with PackageName:'$PackageName' Component:'$Component' VisualStudioYear:'$VisualStudioYear'";
$argumentList = @('remove', "$Component")
Start-VisualStudioModifyOperation -PackageName $PackageName -ArgumentList $argumentList -VisualStudioYear $VisualStudioYear -ApplicableProducts $ApplicableProducts -OperationTexts @('uninstalled', 'uninstalling', 'uninstallation')
}
function Remove-VisualStudioProduct
{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)] [string] $PackageName,
[Parameter(Mandatory = $true)] [string] $Product,
[Parameter(Mandatory = $true)] [string] $VisualStudioYear
)
if ($Env:ChocolateyPackageDebug -ne $null)
{
$VerbosePreference = 'Continue'
$DebugPreference = 'Continue'
Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
}
Write-Debug "Running 'Remove-VisualStudioProduct' with PackageName:'$PackageName' Product:'$Product' VisualStudioYear:'$VisualStudioYear'";
Start-VisualStudioModifyOperation -PackageName $PackageName -ArgumentList @() -VisualStudioYear $VisualStudioYear -ApplicableProducts @($Product) -OperationTexts @('uninstalled', 'uninstalling', 'uninstallation') -Operation 'uninstall'
$remainingProductsCount = (Get-WillowInstalledProducts | Measure-Object).Count
Write-Verbose ("Found {0} installed Visual Studio 2017 or later product(s)" -f $remainingProductsCount)
if ($remainingProductsCount -gt 0)
{
Write-Warning "If Chocolatey asks permission to run the Auto Uninstaller, please answer No. Otherwise, you might lose other Visual Studio products installed on your machine."
}
}
function Remove-VisualStudioWorkload
{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)] [string] $PackageName,
[Parameter(Mandatory = $true)] [string] $Workload,
[Parameter(Mandatory = $true)] [string] $VisualStudioYear,
[Parameter(Mandatory = $true)] [string[]] $ApplicableProducts
)
if ($Env:ChocolateyPackageDebug -ne $null)
{
$VerbosePreference = 'Continue'
$DebugPreference = 'Continue'
Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
}
Write-Debug "Running 'Remove-VisualStudioWorkload' with PackageName:'$PackageName' Workload:'$Workload' VisualStudioYear:'$VisualStudioYear'";
Start-VisualStudioModifyOperation -PackageName $PackageName -ArgumentList @('remove', "Microsoft.VisualStudio.Workload.$Workload") -VisualStudioYear $VisualStudioYear -ApplicableProducts $ApplicableProducts -OperationTexts @('uninstalled', 'uninstalling', 'uninstallation')
}
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 Start-VisualStudioModifyOperation
{
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory = $true)] [string] $PackageName,
[AllowEmptyCollection()] [AllowEmptyString()] [Parameter(Mandatory = $true)] [string[]] $ArgumentList,
[Parameter(Mandatory = $true)] [string] $VisualStudioYear,
[Parameter(Mandatory = $true)] [string[]] $ApplicableProducts,
[Parameter(Mandatory = $true)] [string[]] $OperationTexts,
[ValidateSet('modify', 'uninstall')] [string] $Operation = 'modify',
[string] $InstallerPath
)
Write-Debug "Running 'Start-VisualStudioModifyOperation' with PackageName:'$PackageName' ArgumentList:'$ArgumentList' VisualStudioYear:'$VisualStudioYear' ApplicableProducts:'$ApplicableProducts' OperationTexts:'$OperationTexts' Operation:'$Operation' InstallerPath:'$InstallerPath'";
$frobbed, $frobbing, $frobbage = $OperationTexts
if ($InstallerPath -eq '')
{
$installer = Get-VisualStudioInstaller
if ($installer -eq $null)
{
throw "Unable to determine the location of the Visual Studio Installer. Is Visual Studio $VisualStudioYear installed?"
}
$InstallerPath = $installer.Path
}
$packageParameters = Parse-Parameters $env:chocolateyPackageParameters
for ($i = 0; $i -lt $ArgumentList.Length; $i += 2)
{
$packageParameters[$ArgumentList[$i]] = $ArgumentList[$i + 1]
}
$packageParameters['norestart'] = ''
if (-not $packageParameters.ContainsKey('quiet') -and -not $packageParameters.ContainsKey('passive'))
{
$packageParameters['quiet'] = ''
}
# --no-foo cancels --foo
$negativeSwitches = $packageParameters.GetEnumerator() | Where-Object { $_.Key -match '^no-.' -and $_.Value -eq '' } | Select-Object -ExpandProperty Key
foreach ($negativeSwitch in $negativeSwitches)
{
if ($negativeSwitch -eq $null)
{
continue
}
$packageParameters.Remove($negativeSwitch.Substring(3))
$packageParameters.Remove($negativeSwitch)
}
$argumentSets = ,$packageParameters
if ($packageParameters.ContainsKey('installPath'))
{
if ($packageParameters.ContainsKey('productId'))
{
Write-Warning 'Parameter issue: productId is ignored when installPath is specified.'
}
if ($packageParameters.ContainsKey('channelId'))
{
Write-Warning 'Parameter issue: channelId is ignored when installPath is specified.'
}
}
elseif ($packageParameters.ContainsKey('productId'))
{
if (-not $packageParameters.ContainsKey('channelId'))
{
throw "Parameter error: when productId is specified, channelId must be specified, too."
}
}
elseif ($packageParameters.ContainsKey('channelId'))
{
throw "Parameter error: when channelId is specified, productId must be specified, too."
}
else
{
$installedProducts = Get-WillowInstalledProducts -VisualStudioYear $VisualStudioYear
if (($installedProducts | Measure-Object).Count -eq 0)
{
throw "Unable to detect any supported Visual Studio $VisualStudioYear product. You may try passing --installPath or both --productId and --channelId parameters."
}
if ($Operation -eq 'modify')
{
if ($packageParameters.ContainsKey('add'))
{
$packageIdsList = $packageParameters['add']
$unwantedPackageSelector = { $productInfo.selectedPackages.ContainsKey($_) }
$unwantedStateDescription = 'contains'
}
elseif ($packageParameters.ContainsKey('remove'))
{
$packageIdsList = $packageParameters['remove']
$unwantedPackageSelector = { -not $productInfo.selectedPackages.ContainsKey($_) }
$unwantedStateDescription = 'does not contain'
}
else
{
throw "Unsupported scenario: neither 'add' nor 'remove' is present in parameters collection"
}
}
elseif ($Operation -eq 'uninstall')
{
$packageIdsList = ''
$unwantedPackageSelector = { $false }
$unwantedStateDescription = '<unused>'
}
else
{
throw "Unsupported Operation: $Operation"
}
$packageIds = ($packageIdsList -split ' ') | ForEach-Object { $_ -split ';' | Select-Object -First 1 }
$applicableProductIds = $ApplicableProducts | ForEach-Object { "Microsoft.VisualStudio.Product.$_" }
Write-Debug ('This package supports Visual Studio product id(s): {0}' -f ($applicableProductIds -join ' '))
$argumentSets = @()
foreach ($productInfo in $installedProducts)
{
$applicable = $false
$thisProductIds = $productInfo.selectedPackages.Keys | Where-Object { $_ -like 'Microsoft.VisualStudio.Product.*' }
Write-Debug ('Product at path ''{0}'' has product id(s): {1}' -f $productInfo.installationPath, ($thisProductIds -join ' '))
foreach ($thisProductId in $thisProductIds)
{
if ($applicableProductIds -contains $thisProductId)
{
$applicable = $true
}
}
if (-not $applicable)
{
Write-Verbose ('Product at path ''{0}'' will not be modified because it does not support package(s): {1}' -f $productInfo.installationPath, $packageIds)
continue
}
$unwantedPackages = $packageIds | Where-Object $unwantedPackageSelector
if (($unwantedPackages | Measure-Object).Count -gt 0)
{
Write-Verbose ('Product at path ''{0}'' will not be modified because it already {1} package(s): {2}' -f $productInfo.installationPath, $unwantedStateDescription, ($unwantedPackages -join ' '))
continue
}
$argumentSet = $packageParameters.Clone()
$argumentSet['installPath'] = $productInfo.installationPath
$argumentSets += $argumentSet
}
}
$overallExitCode = 0
foreach ($argumentSet in $argumentSets)
{
if ($argumentSet.ContainsKey('installPath'))
{
Write-Debug "Modifying Visual Studio product: [installPath = '$($argumentSet.installPath)']"
}
else
{
Write-Debug "Modifying Visual Studio product: [productId = '$($argumentSet.productId)' channelId = '$($argumentSet.channelId)']"
}
foreach ($kvp in $argumentSet.Clone().GetEnumerator())
{
if ($kvp.Value -match '^(([^"].*\s)|(\s))')
{
$argumentSet[$kvp.Key] = '"{0}"' -f $kvp.Value
}
}
$silentArgs = $Operation + (($argumentSet.GetEnumerator() | ForEach-Object { ' --{0} {1}' -f $_.Key, $_.Value }) -join '')
$exitCode = -1
if ($PSCmdlet.ShouldProcess("Executable: $InstallerPath", "Start with arguments: $silentArgs"))
{
$exitCode = Start-VSChocolateyProcessAsAdmin -statements $silentArgs -exeToRun $InstallerPath -validExitCodes @(0, 3010)
}
if ($overallExitCode -eq 0)
{
$overallExitCode = $exitCode
}
}
$Env:ChocolateyExitCode = $overallExitCode
if ($overallExitCode -eq 3010)
{
Write-Warning "${PackageName} has been ${frobbed}. However, a reboot is required to finalize the ${frobbage}."
}
}
# based on Start-ChocolateyProcessAsAdmin (8734611), included here only slightly modified (renamed, stricter parameter binding), to add exit code support to old Chocolatey
function Start-VSChocolateyProcessAsAdmin {
[CmdletBinding()]
param(
[string] $statements,
[string] $exeToRun = 'powershell',
[switch] $minimized,
[switch] $noSleep,
[int[]]$validExitCodes = @(0)
)
Write-Debug "Running 'Start-VSChocolateyProcessAsAdmin' with exeToRun:'$exeToRun', statements:'$statements', minimized:$minimized, noSleep:$noSleep, validExitCodes:'$validExitCodes'";
$wrappedStatements = $statements
if ($wrappedStatements -eq $null) { $wrappedStatements = ''}
if ($exeToRun -eq 'powershell') {
$exeToRun = "$($env:SystemRoot)\System32\WindowsPowerShell\v1.0\powershell.exe"
$importChocolateyHelpers = ""
Get-ChildItem "$helpersPath" -Filter *.psm1 | ForEach-Object { $importChocolateyHelpers = "& import-module -name `'$($_.FullName)`';$importChocolateyHelpers" };
$block = @"
`$noSleep = `$$noSleep
$importChocolateyHelpers
try{
`$progressPreference="SilentlyContinue"
$statements
if(!`$noSleep){start-sleep 6}
}
catch{
if(!`$noSleep){start-sleep 8}
throw
}
"@
$encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($block))
$wrappedStatements = "-NoProfile -ExecutionPolicy bypass -EncodedCommand $encoded"
$dbgMessage = @"
Elevating Permissions and running powershell block:
$block
This may take a while, depending on the statements.
"@
}
else
{
$dbgMessage = @"
Elevating Permissions and running [`"$exeToRun`" $wrappedStatements]. This may take a while, depending on the statements.
"@
}
Write-Debug $dbgMessage
$exeIsTextFile = [System.IO.Path]::GetFullPath($exeToRun) + ".istext"
if (([System.IO.File]::Exists($exeIsTextFile))) {
Set-StrictMode -Off
Set-PowerShellExitCode 4
throw "The file was a text file but is attempting to be run as an executable - '$exeToRun'"
}
if ($exeToRun -eq 'msiexec' -or $exeToRun -eq 'msiexec.exe') {
$exeToRun = "$($env:SystemRoot)\System32\msiexec.exe"
}
if (!([System.IO.File]::Exists($exeToRun)) -and $exeToRun -notmatch 'msiexec') {
Write-Warning "May not be able to find '$exeToRun'. Please use full path for executables."
# until we have search paths enabled, let's just pass a warning
#Set-PowerShellExitCode 2
#throw "Could not find '$exeToRun'"
}
# Redirecting output slows things down a bit.
$writeOutput = {
if ($EventArgs.Data -ne $null) {
Write-Host "$($EventArgs.Data)"
}
}
$writeError = {
if ($EventArgs.Data -ne $null) {
Write-Error "$($EventArgs.Data)"
}
}
$process = New-Object System.Diagnostics.Process
$process.EnableRaisingEvents = $true
Register-ObjectEvent -InputObject $process -SourceIdentifier "LogOutput_ChocolateyProc" -EventName OutputDataReceived -Action $writeOutput | Out-Null
Register-ObjectEvent -InputObject $process -SourceIdentifier "LogErrors_ChocolateyProc" -EventName ErrorDataReceived -Action $writeError | Out-Null
#$process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo($exeToRun, $wrappedStatements)
# in case empty args makes a difference, try to be compatible with the older
# version
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $exeToRun
if ($wrappedStatements -ne '') {
$psi.Arguments = "$wrappedStatements"
}
$process.StartInfo = $psi
# process start info
$process.StartInfo.RedirectStandardOutput = $true
$process.StartInfo.RedirectStandardError = $true
$process.StartInfo.UseShellExecute = $false
$process.StartInfo.WorkingDirectory = Get-Location
if ([Environment]::OSVersion.Version -ge (New-Object 'Version' 6,0)){
Write-Debug "Setting RunAs for elevation"
$process.StartInfo.Verb = "RunAs"
}
if ($minimized) {
$process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Minimized
}
$process.Start() | Out-Null
if ($process.StartInfo.RedirectStandardOutput) { $process.BeginOutputReadLine() }
if ($process.StartInfo.RedirectStandardError) { $process.BeginErrorReadLine() }
$process.WaitForExit()
# For some reason this forces the jobs to finish and waits for
# them to do so. Without this it never finishes.
Unregister-Event -SourceIdentifier "LogOutput_ChocolateyProc"
Unregister-Event -SourceIdentifier "LogErrors_ChocolateyProc"
$exitCode = $process.ExitCode
$process.Dispose()
Write-Debug "Command [`"$exeToRun`" $wrappedStatements] exited with `'$exitCode`'."
if ($validExitCodes -notcontains $exitCode) {
Set-StrictMode -Off
Set-PowerShellExitCode $exitCode
throw "Running [`"$exeToRun`" $statements] was not successful. Exit code was '$exitCode'. See log for possible error messages."
}
Write-Debug "Finishing 'Start-VSChocolateyProcessAsAdmin'"
return $exitCode
}
function Start-VSServicingOperation
{
[CmdletBinding()]
param(
[string] $packageName,
[string] $silentArgs,
[string] $file,
[string] $logFilePath,
[string[]] $operationTexts,
[switch] $assumeNewVS2017Installer
)
Write-Debug "Running 'Start-VSServicingOperation' for $packageName with silentArgs:'$silentArgs', file:'$file', logFilePath:$logFilePath', operationTexts:'$operationTexts', assumeNewVS2017Installer:'$assumeNewVS2017Installer'"
$frobbed, $frobbing, $frobbage = $operationTexts
$successExitCodes = @(
0 # success
)
$rebootExitCodes = @(
3010 # success, restart required
)
$priorRebootRequiredExitCodes = @(
-2147185721 # Restart is required before (un)installation can continue
)
$blockExitCodes = @(
-2147205120, # block, restart not required
-2147172352 # block, restart required
)
$validExitCodes = @()
if (($successExitCodes | Measure-Object).Count -gt 0) { $validExitCodes += $successExitCodes }
if (($rebootExitCodes | Measure-Object).Count -gt 0) { $validExitCodes += $rebootExitCodes }
if (($priorRebootRequiredExitCodes | Measure-Object).Count -gt 0) { $validExitCodes += $priorRebootRequiredExitCodes }
if (($blockExitCodes | Measure-Object).Count -gt 0) { $validExitCodes += $blockExitCodes }
$exitCode = Start-VSChocolateyProcessAsAdmin -statements $silentArgs -exeToRun $file -validExitCodes $validExitCodes
if ($assumeNewVS2017Installer)
{
# Not only does a process remain running after vs_installer /uninstall finishes, but that process
# pops up a message box at end! Sheesh.
Write-Debug 'Looking for vs_installer.windows.exe processes spawned by the uninstaller'
$installerProcesses = Get-Process -Name 'vs_installer.windows' -ErrorAction SilentlyContinue
$installerProcessesCount = ($installerProcesses | Measure-Object).Count
if ($installerProcessesCount -gt 0)
{
Write-Debug "Found $installerProcessesCount vs_installer.windows.exe process(es): $($installerProcesses | Select-Object -ExpandProperty Id)"
Write-Debug "Waiting for all vs_installer.windows.exe processes to become input-idle"
foreach ($p in $installerProcesses)
{
[void] $p.Handle # make sure we get the exit code http://stackoverflow.com/a/23797762/266876
$p.WaitForInputIdle()
}
Write-Debug "Sending CloseMainWindow to all vs_installer.windows.exe processes"
foreach ($p in $installerProcesses)
{
$p.CloseMainWindow()
}
Write-Debug "Waiting for all vs_installer.windows.exe processes to exit"
$installerProcesses | Wait-Process
foreach ($proc in $installerProcesses)
{
if ($proc.ExitCode -ne 0)
{
Write-Warning "vs_installer.windows.exe process $($proc.Id) exited with code $($proc.ExitCode)"
if ($exitCode -eq 0)
{
$exitCode = $proc.ExitCode
}
}
else
{
Write-Debug "vs_installer.windows.exe process $($proc.Id) exited with code $($proc.ExitCode)"
}
}
}
else
{
Write-Debug 'Did not find any running vs_installer.windows.exe processes.'
}
}
$Env:ChocolateyExitCode = $exitCode
$warnings = @()
if (($blockExitCodes | Measure-Object).Count -gt 0 -and $blockExitCodes -contains $exitCode)
{
$exceptionMessage = "${packageName} cannot be ${frobbed} on this system."
$success = $false
if ($logFilePath -ne '' -and (Test-Path -Path $logFilePath))
{
# [0C40:07D8][2016-05-28T23:17:32]i000: MUX: Stop Block: MinimumOSLevel : This version of Visual Studio requires a computer with a !$!http://go.microsoft.com/fwlink/?LinkID=647155&clcid=0x409!,!newer version of [email protected]!.
# [0C40:07D8][2016-05-28T23:17:32]i000: MUX: Stop Block: SystemRebootPendingBlock : The computer needs to be restarted before setup can continue. Please restart the computer and run setup again.
$blocks = Get-Content -Path $logFilePath `
| Select-String '(?<=Stop Block: ).+$' `
| Select-Object -ExpandProperty Matches `
| Where-Object { $_.Success -eq $true } `
| Select-Object -ExpandProperty Value `
| Sort-Object -Unique
if (($blocks | Measure-Object).Count -gt 0)
{
$warnings = @("${packageName} cannot be ${frobbed} due to the following issues:") + $blocks
$exceptionMessage += " You may attempt to fix the issues listed and try again."
}
}
}
elseif (($priorRebootRequiredExitCodes | Measure-Object).Count -gt 0 -and $priorRebootRequiredExitCodes -contains $exitCode)
{
$exceptionMessage = "The computer must be rebooted before ${frobbing} ${packageName}. Please reboot the computer and run the ${frobbage} again."
$success = $false
}
elseif (($rebootExitCodes | Measure-Object).Count -gt 0 -and $rebootExitCodes -contains $exitCode)
{
$needsReboot = $true
$success = $true
}
else
{
$needsReboot = $false
$success = $true
}
if ($success)
{
if ($needsReboot)
{
Write-Warning "${packageName} has been ${frobbed}. However, a reboot is required to finalize the ${frobbage}."
}
else
{
Write-Host "${packageName} has been ${frobbed}."
}
}
else
{
if ($warnings -ne $null)
{
$warnings | Write-Warning
}
throw $exceptionMessage
}
}
function Uninstall-VisualStudio {
<#
.SYNOPSIS
Uninstalls Visual Studio
.DESCRIPTION
Uninstalls Visual Studio.
.PARAMETER PackageName
The name of the VisualStudio package.
.PARAMETER ApplicationName
The VisualStudio app name - i.e. 'Microsoft Visual Studio Community 2015'.
.PARAMETER UninstallerName
This name of the installer executable - i.e. 'vs_community.exe'.
.EXAMPLE
Uninstall-VisualStudio 'VisualStudio2015Community' 'Microsoft Visual Studio Community 2015' 'vs_community.exe'
.OUTPUTS
None
.NOTES
This helper reduces the number of lines one would have to write to uninstall Visual Studio.
This method has no error handling built into it.
.LINK
Uninstall-ChocolateyPackage
#>
[CmdletBinding()]
param(
[string] $PackageName,
[string] $ApplicationName,
[string] $UninstallerName,
[ValidateSet('MsiVS2015OrEarlier', 'WillowVS2017OrLater')] [string] $InstallerTechnology,
[string] $ProgramsAndFeaturesDisplayName = $ApplicationName
)
if ($Env:ChocolateyPackageDebug -ne $null)
{
$VerbosePreference = 'Continue'
$DebugPreference = 'Continue'
Write-Warning "VerbosePreference and DebugPreference set to Continue due to the presence of ChocolateyPackageDebug environment variable"
}
Write-Debug "Running 'Uninstall-VisualStudio' for $PackageName with ApplicationName:'$ApplicationName' UninstallerName:'$UninstallerName' InstallerTechnology:'$InstallerTechnology' ProgramsAndFeaturesDisplayName:'$ProgramsAndFeaturesDisplayName'";
$assumeNewVS2017Installer = $InstallerTechnology -eq 'WillowVS2017OrLater'
$packageParameters = Parse-Parameters $env:chocolateyPackageParameters
if ($assumeNewVS2017Installer)
{
$vsInstaller = Get-VisualStudioInstaller
if ($vsInstaller -eq $null)
{
Write-Warning "Uninstall information for $PackageName could not be found. This probably means the application was uninstalled outside Chocolatey."
return
}
$uninstallerPath = $vsInstaller.Path
$logFilePath = $null
}
else
{
$uninstallerPath = Get-VSUninstallerExePath `
-PackageName $PackageName `
-UninstallerName $UninstallerName `
-ProgramsAndFeaturesDisplayName $ProgramsAndFeaturesDisplayName `
-AssumeNewVS2017Installer:$assumeNewVS2017Installer
$logFilePath = Join-Path $Env:TEMP "${PackageName}_uninstall.log"
Write-Debug "Log file path: $logFilePath"
}
$silentArgs = Generate-UninstallArgumentsString -parameters $packageParameters -logFilePath $logFilePath -assumeNewVS2017Installer:$assumeNewVS2017Installer
$arguments = @{
packageName = $PackageName
silentArgs = $silentArgs
file = $uninstallerPath
assumeNewVS2017Installer = $assumeNewVS2017Installer
}
$argumentsDump = ($arguments.GetEnumerator() | ForEach-Object { '-{0}:''{1}''' -f $_.Key,"$($_.Value)" }) -join ' '
Write-Debug "Uninstall-VSChocolateyPackage $argumentsDump"
Uninstall-VSChocolateyPackage @arguments
}
# 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 { $_.GetAttribute('Hidden') -eq 'no' -and $_.GetAttribute('Selected') -eq 'yes' } | Select-Object -ExpandProperty Id
$selectedFeatures = New-Object System.Collections.ArrayList
$invalidFeatures = New-Object System.Collections.ArrayList
foreach ($feature in $features)
{
$node = $selectableItemCustomizations.SelectSingleNode("*[@Id=""$feature""]")
if ($node -ne $null)
{
$node.Selected = "yes"
$selectedFeatures.Add($feature) | Out-Null
}
else
{
$invalidFeatures.Add($feature) | Out-Null
}
}
if ($invalidFeatures.Count -gt 0)
{
$errorMessage = "Invalid feature name(s): $invalidFeatures"
$validFeatureNames = $selectableItemCustomizations.ChildNodes | Select-Object -ExpandProperty Id
Write-Warning $errorMessage
Write-Warning "Valid feature names are: $validFeatureNames"
throw $errorMessage
}
Write-Verbose "Features selected by default: $featuresSelectedByDefault"
Write-Verbose "Features selected using package parameters: $selectedFeatures"
$xml.Save($adminFile)
}
# chocolatey-visualstudio.extension
This is a Chocolatey extension that simplifies building Chocolatey packages which install and configure Microsoft Visual Studio.
## Functions
### Install-VisualStudio
Installs a product from the Visual Studio family (Professional, Enterprise, Community, Build Tools etc.).
Supports both the classic MSI installer of Visual Studio up to 2017 Preview 3 and the new "Willow" installer of Visual Studio 2017 RC.
### Uninstall-VisualStudio
For Visual Studio editions using the classic MSI installer (Visual Studio up to 2017 Preview 3), uninstalls an installed product
from the Visual Studio family (Professional, Enterprise, Community, Build Tools etc.).
For Visual Studio editions using the new "Willow" installer of Visual Studio 2017 RC, uninstalls the Visual Studio Installer
and all installed products from the Visual Studio 2017 family.
### Add-VisualStudioWorkload
Adds a workload (a set of features) to installed products from the Visual Studio 2017 family.
Supports the new "Willow" installer of Visual Studio 2017 RC only.
### Remove-VisualStudioWorkload
Removes a workload (a set of features) from installed products from the Visual Studio 2017 family.
Supports the new "Willow" installer of Visual Studio 2017 RC only.
### Add-VisualStudioComponent
Adds a component (an individual feature) to installed products from the Visual Studio 2017 family.
Supports the new "Willow" installer of Visual Studio 2017 RC only.
### Remove-VisualStudioComponent
Removes a component (an individual feature) from installed products from the Visual Studio 2017 family.
Supports the new "Willow" installer of Visual Studio 2017 RC only.
### Remove-VisualStudioProduct
Removes an installed product from the Visual Studio 2017 family (Professional, Enterprise, Community, Build Tools etc.).
Supports the new "Willow" installer of Visual Studio 2017 RC only.
### Get-VisualStudioInstance
Returns information about all Visual Studio instances installed on the machine.
The returned objects contain properties: InstallationPath, InstallationVersion, ProductId, ChannelId.
The last two properties have values only for instances of Visual Studio 2017.
### Get-VisualStudioInstaller
Returns information about the Visual Studio Installer, if installed on the machine.
The returned object contain properties: Path, Version.
Supports the new "Willow" installer of Visual Studio 2017 RC only.
### Install-VisualStudioInstaller
Installs or updates the Visual Studio Installer.
Supports the new "Willow" installer of Visual Studio 2017 RC only.
## Installation
End users typically do not install this package directly - it is usually installed automatically as a dependency of another package.
Package authors interested in testing the usage of individual functions may install this package via Chocolatey: `choco install chocolatey-visualstudio.extension`.
## Usage
To be able to use functions from this extension in a Chocolatey package, add the following to the `nuspec` specification:
<dependencies>
<dependency id="chocolatey-visualstudio.extension" version="SPECIFY_LATEST_VERSION" />
</dependencies>
**NOTE**: Make sure you use adequate _minimum_ version.
## Testing
To test the functions you can import the module directly or via the `chocolateyInstaller.psm1` module:
PS> Import-Module $Env:ChocolateyInstall\helpers\chocolateyInstaller.psm1
PS> Import-Module $Env:ChocolateyInstall\extensions\chocolatey-visualstudio\*.psm1
You can now test any of the functions:
PS> Install-VisualStudio `
-PackageName 'visualstudio2017enterprise' `
-ApplicationName 'Microsoft Visual Studio Enterprise 2017 RC' `
-Url 'https://download.microsoft.com/download/4/2/9/429C6D6F-543E-4BB4-A2C7-4EFA7F8DE59D/vs_Enterprise.exe' `
-Checksum '493364F350657B537077E72E7400DBF8875CD773' `
-ChecksumType 'SHA1' `
-InstallerTechnology 'WillowVS2017OrLater' `
-ProgramsAndFeaturesDisplayName 'Microsoft Visual Studio 2017'
PS> Add-VisualStudioWorkload `
-PackageName 'visualstudio2017-workload-manageddesktop' `
-Workload 'Microsoft.VisualStudio.Workload.ManagedDesktop' `
-VisualStudioYear '2017' `
-ApplicableProducts @('Community', 'Professional', 'Enterprise')
PS> Remove-VisualStudioWorkload `
-PackageName 'visualstudio2017-workload-manageddesktop' `
-Workload 'Microsoft.VisualStudio.Workload.ManagedDesktop' `
-VisualStudioYear '2017' `
-ApplicableProducts @('Community', 'Professional', 'Enterprise')
PS> Uninstall-VisualStudio `
-PackageName 'visualstudio2017enterprise' `
-ApplicationName 'Microsoft Visual Studio Enterprise 2017 RC' `
-UninstallerName 'vs_installer.exe' `
-InstallerTechnology 'WillowVS2017OrLater' `
-ProgramsAndFeaturesDisplayName 'Microsoft Visual Studio 2017'
# this must be run from a script and requires the presence of an AdminDeployment.xml file next to the script
Install-VisualStudio `
-PackageName 'visualstudio2017enterprise' `
-ApplicationName 'Microsoft Visual Studio Enterprise 15 Preview 3' `
-Url 'https://download.microsoft.com/download/e/e/6/ee6e936e-6323-4b51-a6f3-7b276b7e168a/vs_enterprise.exe' `
-Checksum '6A63984CAFE972D655817395CC12054068077015' `
-ChecksumType 'SHA1' `
-InstallerTechnology 'MsiVS2015OrEarlier'
Keep in mind that functions may work fully only in the context of the `chocolateyInstaller` module.
To get the list of functions, load the module directly and invoke the following command:
Get-Command -Module chocolatey-visualstudio
To get help for a specific function use the [help](https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/get-help) command:
help Install-VisualStudio -Full
### Acknowledgement
The structure of the Markdown files was inspired by [chocolatey-core.extension](https://github.com/chocolatey/chocolatey-coreteampackages/tree/master/extensions/chocolatey-core.extension).
The module code was initially based on the logic of the `visualstudio2015community` package, later extensively expanded and improved in the `visualstudio2017enterprise` package.
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 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.